[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\n";
    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\n", 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);
}

posted @ 2013-12-17 17:38  小尼人00  阅读(472)  评论(0编辑  收藏  举报