C语言文件锁

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

C语⾔⽂件锁mkfifo.c⽂件
1 #include<sys/types.h>
2 #include<sys/stat.h>
3 #include<stdio.h>
4 #include<errno.h>
5
6int main()
7 {
8//int mkfifo(const char *pathname, mode_t mode);
9
10int ret=mkfifo("./test",0777);
11if(ret<0)
12 {
13if(errno==EEXIST)
14 {
15 printf("create error errno=%d\n",errno);
16return -1;
17 }
18 }
19 }
file_read.c⽂件
1 #include<unistd.h>
2 #include<fcntl.h>
3 #include<stdio.h>
4 #include<errno.h>
5int main()
6 {
7int fd;
8 fd=open("./test",O_RDONLY);
9if(fd<0)
10 {
11 perror("open failed\n");
12return -1;
13 }
14
15//int fcntl(int fd,int cmd,.../* arg */ );
16//设置读锁
17struct flock lock;
18lock.l_type=F_RDLCK;
19lock.l_whence=SEEK_SET;
20lock.l_start=0;
21lock.l_len=100;
22
23//上锁
24char buf[1024];
25int ret=fcntl(fd,F_SETLKW,&lock);
26//使⽤资源
27 printf("read...\n");
28 ret=read(fd,buf,100);
29if(ret<=0)
30 {
31 printf("read errer\n");
32return -1;
33 }
34 puts(buf);
35
36//解锁
37lock.l_type=F_UNLCK;
38lock.l_whence=SEEK_SET;
39lock.l_start=0;
40lock.l_len=100;
41 fcntl(fd,F_SETLKW,&lock);
42 close(fd);
43 }
file_write.c⽂件
1 #include<unistd.h>
2 #include<fcntl.h>
3 #include<stdio.h>
4 #include<errno.h>
5int main()
6 {
7int fd;
8 fd=open("./test",O_WRONLY);
9if(fd<0)
10 {
11 perror("open failed\n");
12return -1;
13 }
14
15//int fcntl(int fd,int cmd,.../* arg */ );
16//设置读锁
17struct flock lock;
18lock.l_type=F_RDLCK;
19lock.l_whence=SEEK_SET;
20lock.l_start=0;
21lock.l_len=100;
22
23//上锁
24char buf[1024];
25int ret=fcntl(fd,F_SETLKW,&lock);
26//使⽤资源
27 printf("write...\n");
28 ret=write(fd,"yisheng",8);
29if(ret<=0)
30 {
31 printf("write errer\n");
32return -1;
33 }
34 sleep(20);
35 printf("unlock...\n");
36
37//解锁
38lock.l_type=F_UNLCK;
39lock.l_whence=SEEK_SET;
40lock.l_start=0;
41lock.l_len=100;
42 fcntl(fd,F_SETLKW,&lock);
43 close(fd);
44 }
gcc mkfifo.c ./a.out ⽣成test
gcc file_read.c -o read gcc file_write.c -o write ./read和./write,效果如下:。

相关文档
最新文档