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
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。