Linux C++ 进程间通信-PIPE

PIPE

  • 匿名管道,用于父子进程或者亲戚进程之间的通信
  • 函数 int pipe(int fd[2])
  • 头文件#include <unistd.h>
  • 实现代码
#include <unistd.h>
#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    int pid = fork();

    int fd[2]={0};
    if (pipe(fd) < 0){
        cout << "pipe error" << endl;
        return -1;
    }
    char buf[128] {0};
    cout << "pid:" << pid << ";" << fd[0] << ";" << fd[1] << endl;

    if (pid > 0) {
        // 父进程
        close(fd[1]); // 关闭写端
        cout << "等待子进程输入" << endl;
        read(fd[0], buf, 128);
        cout << "子进程输入: " << buf << endl;
        close(fd[0]);
    } else if (pid == 0) {
        // 子进程
        close(fd[0]);  // 关闭读端
        sleep(1);
        sprintf(buf, "hello");
        cout << "子进程输入"  << buf << endl;
        write(fd[1], buf, sizeof(buf));
        // close(fd[1]);
    } else {
        cout << "fork error" << endl;
        return -1;
    }
    if (pid > 0) {
    	// 等待子进程结束
        int status;
        waitpid(pid, &status, 0);
    }
    return 0;
}
  • 代码实现的是子进程输入,父进程输出。
  • 几个问题
  1. 为什么要在进入子进程的时候关闭读端,进入父进程的时候关闭写端。
    可以查看cout << "pid:" << pid << ";" << fd[0] << ";" << fd[1] << endl;。不关事子进程还是父进程对于fd的输出是一致的。产生这种写过的原因是pipe函数在父子进程之间创建的机制决定的
  2. 为什么子进程关闭了读端,父进程还能读取。父进程关闭了写端,子进程还能写入。
    这个其实和共享指针类似,Linux系统对于fd描述符的拷贝也是存在一个计数器,,每次close只是将计数器减1,直到计数器为0才是真实的关闭。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值