首页 / 更多教程 / 进程间通信--FIFO(命名管道)
进程间通信--FIFO(命名管道)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了进程间通信--FIFO(命名管道),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1487字,纯文字阅读大概需要3分钟。
内容图文
匿名管道只能解决具有亲缘关系的进程间通信,但是任意两个进程间不能通信。
FIFO不同于管道之处在于提供了一个路径名与之关联,以FIFO的文件形式存储到文件系统中。
命名管道是一个设备文件,因此进程间不需要亲缘关系,只要可以访问与之关联的路径即可,就能同FIFO通信
命名管道通过mkfifo命名一个管道,然后通过open read write进行文件读写
管道可以根据open选项设置阻塞非阻塞
注意:命名管道可能出现粘包的问题
命名管道代码示例:
server.cpp #include<iostream> #include<stdlib.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include <unistd.h> int main(){ unlink("../myfifo"); int ret = mkfifo("../myfifo",S_IFIFO|0666); if (ret == -1) { printf("fifo create err\n"); return -1; } int fd = open("../myfifo",O_RDWR); if (fd == -1) { printf("open file err\n"); return -1; } int n = 0; while(1) { char buf[1024] = {0}; n = read(fd,buf,1024); if(n > 0) { printf("recv[%d]%s\n",n,buf); } else { printf("recv buf[%d] failed\n",n); break; } } close(fd); }
client.cpp #include <iostream> #include <stdlib.h> #include <sys/types.h> #include <fcntl.h> #include <sys/types.h> #include <unistd.h> #include <string.h> int main(){ int fd = open("../myfifo",O_RDWR); if (fd == -1) { printf("open fifo file err\n"); return -1; } int num = 10; char buf[1024] = {0}; while(num--) { sprintf(buf,"hello server,..num=%d\n",num); if(write(fd,buf,strlen(buf)) == -1) { printf("write fifo err\n"); return -1; } usleep(100); } close(fd); }
内容总结
以上是互联网集市为您收集整理的进程间通信--FIFO(命名管道)全部内容,希望文章能够帮你解决进程间通信--FIFO(命名管道)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。