进程同步(一)—— 管道

父子进程可以通过管道进行数据交互,一个管道只能有一个数据流向,要实现双工通信,可以使用两个管道实现。

管道工作原理:

  1. 向内核申请管道描述符
  2. 父子进程fork()后均有该管道资源,但处于不同内存地址
  3. 通过对描述符读写实现通信

数据交互图:

image 

单工通信代码实现:

 1 #include <stdio.h> 
 2 #include <string.h> 
 3 #include <unistd.h> 
 4 #include <iostream>
 5 
 6 using namespace std;
 7 
 8 const int MAX_BUFFSIZE = 1024;
 9 
10 int main() 
11 { 
12     int    pipe_fd[2]; 
13     pid_t pid;  
14     char buff[MAX_BUFFSIZE]; 
15     
16     memset(buff,'',sizeof(buff));
17     
18     if (pipe(pipe_fd) < 0) 
19     {
20           cout<<"pipe create error"; 
21     }
22 
23     if ((pid = fork()) < 0) 
24     {
25         cout<<"fork error"; 
26     }
27     
28     if (pid > 0)
29     { 
30         close(pipe_fd[0]);
31         cin>>buff;
32         write(pipe_fd[1],buff,sizeof(buff));
33     } 
34     if (pid == 0)
35     { 
36         close(pipe_fd[1]); 
37         if ((read(pipe_fd[0],buff,MAX_BUFFSIZE)) > 0)
38         {
39             cout<<"Msg from parent:"<<buff;
40         }
41     } 
42     return 0; 
43 }

测试结果:

  

原文地址:https://www.cnblogs.com/binchen-china/p/5449702.html