socketpair实现进程通信
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>intmain(){intfd[2];if(socketpair(AF_LOCAL,SOCK_STREAM,0,fd)<0){perror("sockpair");return1;}pid_tid=fork();if(id<0){perror("fork");return2;}elseif(id==0){close(fd[0]);charbuf[1024];while(1){ssize_t_s;strcpy(buf,"hellobit");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]);charbuf[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,"helloworld");write(fd[0],buf,strlen(buf));}close(fd[0]);//waitchild}return0;
运行截图:
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。