前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >进程同步(一)—— 管道

进程同步(一)—— 管道

作者头像
Aichen
发布2018-05-18 11:26:48
1.3K0
发布2018-05-18 11:26:48
举报
文章被收录于专栏:白驹过隙白驹过隙

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

管道工作原理:

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

数据交互图:

image
image

单工通信代码实现:

代码语言:javascript
复制
#include <stdio.h> 
#include <string.h> 
#include <unistd.h> 
#include <iostream>

using namespace std;

const int MAX_BUFFSIZE = 1024;

int main() 
{ 
    int    pipe_fd[2]; 
    pid_t pid;  
    char buff[MAX_BUFFSIZE]; 
    
    memset(buff,'\0',sizeof(buff));
    
    if (pipe(pipe_fd) < 0) 
    {
          cout<<"pipe create error"; 
    }

    if ((pid = fork()) < 0) 
    {
        cout<<"fork error"; 
    }
    
    if (pid > 0)
    { 
        close(pipe_fd[0]);
        cin>>buff;
        write(pipe_fd[1],buff,sizeof(buff));
    } 
    if (pid == 0)
    { 
        close(pipe_fd[1]); 
        if ((read(pipe_fd[0],buff,MAX_BUFFSIZE)) > 0)
        {
            cout<<"Msg from parent:"<<buff;
        }
    } 
    return 0; 
}
 

测试结果:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-04-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档