進程間雙向通信--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





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章