首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

进程同步(一)—— 管道

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

管道工作原理:

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

数据交互图:

单工通信代码实现:

代码语言: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; 
}
 

测试结果:

下一篇
举报
领券