进程间双向通信--sockpair

发布时间:2020-08-01 20:49:31 作者:小镇青苔
来源:网络 阅读:356


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





推荐阅读:
  1. 进程间的通信
  2. 进程间通信:消息队列实现双向通信

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

进程通信 --

上一篇:如何保障企业数据安全

下一篇:使用Seek method做分页时offset predicate的注意事项

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》