Linux系统编程:fifo有名管道的使用
生活随笔
收集整理的这篇文章主要介绍了
Linux系统编程:fifo有名管道的使用
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
fifo介绍
我们可以利用管道进行进程间通信,已经有匿名管道 为啥还要fifo 有名管道呢?有名管道是对匿名管道的一个补充,匿名管道是用在有血缘关系的进程间通信。fifo有名管道呢,可以用在任何进程间通信。
函数原型 int mkfifo(const char *pathname, mode_t mode);第一个参数是匿名管道的路径,第二个参数创建有名管道的权限。当然man 手册是最好的文档,一定要自己试着去看man 手册。
fifo的使用
我们利用2个不相干的进行 通过fifo 有名管道进行通信。下面用fifo_read进程读数据,fifo_write进程写数据。
fifo_read.c
#include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h>int main(int argc,char *argv[]) {if(argc < 2){printf("./fifo_read fifoName");exit(1);}int res = access(argv[1],F_OK);if(res==-1)//不可访问 或者 文件不存在{int re = mkfifo(argv[1],0664);if(re==0){printf("创建fifo文件成功,文件名:%s\n",argv[1]);}else{perror("mkfifo error");exit(1);}}int fd = open(argv[1],O_RDONLY);//从fifo中读数据char temp[1024]={0};while(1){read(fd,temp,sizeof(temp));printf("从fifo中读取数据:%s\n",temp);}close(fd);return 0; }fifo_write.c
#include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h>int main(int argc,char *argv[]) {if(argc < 2){printf("./fifo_write fifoName");exit(1);}int res = access(argv[1],F_OK);if(res==-1)//不可访问 或者 文件不存在{int re = mkfifo(argv[1],0664);if(re==0){printf("创建fifo文件成功,文件名:%s\n",argv[1]);}else{perror("mkfifo error");exit(1);}}int fd = open(argv[1],O_WRONLY);//往fifo中写数据char str[100] = "hello laymond";while(1){sleep(1);write(fd,str,sizeof(str));printf("写入一条数据:%s\n",str);}close(fd);return 0; }代码运行检测
总结
以上是生活随笔为你收集整理的Linux系统编程:fifo有名管道的使用的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 排序算法:冒泡排序算法优化实现及分析
- 下一篇: linux下c/c++实例之socket