标签:enc ges err path close 技术分享 mode types int
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,效果如下:
标签:enc ges err path close 技术分享 mode types int
原文地址:http://www.cnblogs.com/ysjd/p/7667229.html