pipe用来创建管道,但是单个管道只能单向通信,一端用于读,而另一端用于写。如果要实现进程双向通信,必须创建一对管道。具体实现忽略。而socketpair则可以用来创建双向通信的管道。取决于底层实现,打开的还是一个文件,fd[0],fd[1],管道中f[0]读端,f[1]写端。
#include <sys/types.h>
#include <sys/socket.h>
int socketpair(int domain, int type, int protocol, int sv[2]);
domain:选用AF_LOCAL;
type:SOCK_STREAM
protocol:默认0
#include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/socket.h> #include<unistd.h> #include<errno.h> #include<string.h> int main() { int fd[2]; if(socketpair(AF_LOCAL,SOCK_STREAM,0,fd)<0){ perror("sockpair"); return 1; } pid_t id=fork(); if(id<0){ perror("fork"); return 2; } else if(id==0){ close(fd[0]); char buf[1024]; while(1) { ssize_t _s; strcpy(buf,"hello bit"); write(fd[1],buf,strlen(buf)); _s=read(fd[1],buf,sizeof(buf)-1); buf[_s]='\0'; printf("father->child%s\n",buf); } close(fd[1]); } else{ close(fd[1]); char buf[1024]; while(1) { ssize_t _s=read(fd[0],buf,sizeof(buf)-1); if(_s>0){ buf[_s]='\0'; printf("child -> father %s\n",buf); } strcpy(buf,"hello world"); write(fd[0],buf,strlen(buf)); } close(fd[0]); //wait child } return 0;
运行截图:
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网页名称:socketpair实现进程通信-创新互联
本文路径:https://www.cdcxhl.com/article4/dhdeoe.html
成都网站建设公司_创新互联,为您提供全网营销推广、搜索引擎优化、虚拟主机、App开发、网站制作、网站设计
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联