当前位置:   article > 正文

Linux C++ 进程间通信-PIPE_linux c pipe

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 代码实现的是子进程输入,父进程输出。
  • 几个问题
  1. 为什么要在进入子进程的时候关闭读端,进入父进程的时候关闭写端。
    可以查看cout << "pid:" << pid << ";" << fd[0] << ";" << fd[1] << endl;。不关事子进程还是父进程对于fd的输出是一致的。产生这种写过的原因是pipe函数在父子进程之间创建的机制决定的
  2. 为什么子进程关闭了读端,父进程还能读取。父进程关闭了写端,子进程还能写入。
    这个其实和共享指针类似,Linux系统对于fd描述符的拷贝也是存在一个计数器,,每次close只是将计数器减1,直到计数器为0才是真实的关闭。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/837660
推荐阅读
相关标签
  

闽ICP备14008679号