首页 > 系统服务 > 详细

进程通信(一)—— 管道

时间:2016-04-30 23:36:25      阅读:311      评论:0      收藏:0      [点我收藏+]

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

 

管道工作原理:

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

数据交互图:

技术分享 

单工通信代码实现:

 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,\0,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 }

测试结果:

  技术分享

进程通信(一)—— 管道

原文:http://www.cnblogs.com/binchen-china/p/5449702.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!