C语言文件锁

mkfifo.c文件

 1 #include<sys/types.h>
 2 #include<sys/stat.h>
 3 #include<stdio.h>
 4 #include<errno.h>
 5 
 6 int main()
 7 {
 8     //int mkfifo(const char *pathname, mode_t mode);
 9 
10     int ret=mkfifo("./test",0777);
11     if(ret<0)
12     {
13         if(errno==EEXIST)
14         {
15             printf("create error errno=%d\n",errno);
16             return -1;
17         }
18     }
19 }

file_read.c文件

 1 #include<unistd.h>
 2 #include<fcntl.h>
 3 #include<stdio.h>
 4 #include<errno.h>
 5 int main()
 6 {
 7     int fd;
 8     fd=open("./test",O_RDONLY);
 9     if(fd<0)
10     {
11         perror("open failed\n");
12         return -1;
13     }
14 
15     //int fcntl(int fd,int cmd,.../* arg */ );
16     //设置读锁
17     struct flock lock;
18     lock.l_type=F_RDLCK;
19     lock.l_whence=SEEK_SET;
20     lock.l_start=0;
21     lock.l_len=100;
22 
23     //上锁
24     char buf[1024];
25     int ret=fcntl(fd,F_SETLKW,&lock);
26     //使用资源
27     printf("read...\n");
28     ret=read(fd,buf,100);
29     if(ret<=0)
30     {
31         printf("read errer\n");
32         return -1;
33     }
34     puts(buf);
35 
36     //解锁
37     lock.l_type=F_UNLCK;
38     lock.l_whence=SEEK_SET;
39     lock.l_start=0;
40     lock.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>
 5 int main()
 6 {
 7     int fd;
 8     fd=open("./test",O_WRONLY);
 9     if(fd<0)
10     {
11         perror("open failed\n");
12         return -1;
13     }
14 
15     //int fcntl(int fd,int cmd,.../* arg */ );
16     //设置读锁
17     struct flock lock;
18     lock.l_type=F_RDLCK;
19     lock.l_whence=SEEK_SET;
20     lock.l_start=0;
21     lock.l_len=100;
22 
23     //上锁
24     char buf[1024];
25     int ret=fcntl(fd,F_SETLKW,&lock);
26     //使用资源
27     printf("write...\n");
28     ret=write(fd,"yisheng",8);
29     if(ret<=0)
30     {
31         printf("write errer\n");
32         return -1;
33     }
34     sleep(20);
35     printf("unlock...\n");
36 
37     //解锁
38     lock.l_type=F_UNLCK;
39     lock.l_whence=SEEK_SET;
40     lock.l_start=0;
41     lock.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,效果如下:

转载于:https://www.cnblogs.com/ysjd/p/7667229.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值