进程间双向通信--sockpair

sockpair是一个套接字,可以用于网络通信,也可用于本机内进程间通信。

sockpair类似于管道,只不过管道是用于单向通信的,只能一方读,一方写,。而想要用于进程间双向通信,就要pipe两次,创建两个管道。sockpair直接就可以实现进程间双向通信。

  1 #include<stdio.h>
  2 #include<unistd.h>
  3 #include<stdlib.h>
  4 #include<string.h>
  5 #include<sys/types.h>
  6 #include<sys/socket.h>
  7 int main()
  8 {
  9     int fd[2]={0,0};
 10     int sock = socketpair(AF_LOCAL,SOCK_STREAM,0,fd);
 11     if(sock<0)
 12     {
 13         perror("socketpair");
 14         exit(1);
 15     }
 16     pid_t id = fork();
 17     if(id<0)
 18     {
 19         perror("fork");
 20         exit(2);
 21     }
 22     else if(id == 0)
 23     {
 24         close(fd[0]);
 25         char buf[1024];
 26         while(1)
 27         {
 28             memset(buf,'\0',sizeof(buf));
 29             strcpy(buf,"hello world");
 30             write(fd[1],buf,sizeof(buf)-1);
 31             read(fd[1],buf,sizeof(buf)-1);
 32             sleep(1);
 33             printf("father say:%s\n",buf);
 34         }
 35         close(fd[1]);
 36     }
 37     else
 38     {
 39         close(fd[1]);
 40         char buf[1024];
 41         while(1)
 42         {
 43             read(fd[0],buf,sizeof(buf)-1);
 44             printf("child say:%s\n",buf);
 45             memset(buf,'\0',sizeof(buf));
 46             strcpy(buf,"nihao");
 47             write(fd[0],buf,sizeof(buf)-1);
 48             sleep(1);
 49         }
 50         close(fd[0]);
 51     }
 52     return 0;
 53 }
 
 [fbl@localhost socketpair]$ ./my_pair 
child say:hello world
father say:nihao
child say:hello world
father say:nihao
child say:hello world
father say:nihao
child say:hello world

猜你喜欢

转载自blog.csdn.net/we_are_family678/article/details/80315354