[Linux] 由管道父进程向子进程发送数据 (父子间IPC)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <unistd.h>

using std::cin;
using std::cout;
using std::endl;
using std::string;
typedef string String;

const int MAXLINE = 1005;

int main() {
    int n;
    int fd[2];
    pid_t pid;
    char line[MAXLINE];
    cout << "hehe
";
    cout << fd[0] << ' ' << fd[1] << endl;
    if (pipe(fd) < 0) {
        fprintf(stderr, "iipe error");
    }
    if ((pid = fork()) < 0) {
        fprintf(stderr, "fork error");
    }
    else if(pid > 0) { // parent
        cout << "par : " << fd[0] << ' ' << fd[1] << endl;
        close(fd[0]);
        write(fd[1], "hello world
", 12);
    }
    else {
        cout << "son: " << fd[0] << ' ' << fd[1] << endl;
        close(fd[1]);
        n = read(fd[0], line, MAXLINE);
        cout << "n : " << n << endl;
        cout << "line : " << line << endl;
        write(STDOUT_FILENO, line, n);
    }
    exit(0);
}

原文地址:https://www.cnblogs.com/robbychan/p/3786885.html