代码示例_IPC_无名管道

无名管道


 

 

 1 #include <unistd.h>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 
 6 int main(void)
 7 {
 8     char buf[1024];
 9     int pipefd[2];
10 
11     if( pipe( pipefd ) ){  // 创建无名管道
12         perror("pipe failed");
13         exit(1);
14     }
15 
16     pid_t pid = fork();           // fork 亲缘进程通讯
17     if(pid<0){
18         perror("fork failed");
19         exit;
20     }
21 
22 
23     else if(pid>0){                // 父进程发送数据
24         close(pipefd[0]); // 关闭读 
25 
26         while(1){
27             bzero(buf,1024);
28             fgets(buf,1024,stdin);
29             
30             write(pipefd[1],buf,strlen(buf));
31 
32             if(strncmp(buf,"quit",4)==0)
33                 break;
34         }
35         exit(0);
36     }
37 
38     else if(pid==0){                // 子进程接收数据
39         close(pipefd[1]); // 关闭写
40 
41         while(1){
42             bzero(buf,1024);
43             read(pipefd[0],buf,1024);
44             printf("chiid read: %s",buf);
45 
46             if(strncmp(buf,"quit",4)==0)
47                 break;
48         }
49         exit(0);
50     }
51 
52     return 0 ;
53 }

 

 


 

 

 

success !

 

 

 


 

posted @ 2019-06-19 15:17  panda_w  阅读(340)  评论(0编辑  收藏  举报