0

我想使用管道重定向子进程的标准输入和标准输出。

目前我有以下代码:

void child(int pipeIn[], int pipeOut[]) {

    char buff[20];
    const char msg[]="Child Message\n";
    close(pipeIn[1]);
    close(pipeOut[0]);

    if (dup2(pipeIn[0], 0))
        perror("dup2 pipeIn");

    if (dup2(pipeOut[1], 1))
        perror("dup2 pipeOut");

    close(pipeIn[0]);
    close(pipeOut[1]);

    for (int i = 0; i < 10; ++i) {
        read(0, buff, 20);
        fprintf(stderr, "Child: %s\n",buff);
        printf("%s",msg);
    }
}

void parent(int pipeIn[], int pipeOut[]) {

    char buff[20];

    const char msg[]="Parent Message\n";
    close(pipeIn[0]);
    close(pipeOut[1]);

    for (int i = 0; i < 10; ++i) {
        write(pipeIn[1], msg, 16);
        read(pipeOut[0], buff, 50);
        printf("Parent: %s", buff);

    }

}

void test() {

    int pipeOut[2],pipeIn[2];

    if(pipe(pipeOut)) {
        perror("pipeOut");
        exit(1);
    }

    if(pipe(pipeIn)) {
        perror("pipeIn");
        exit(1);
    }

    int pid = fork();

    if (pid == -1) {
        perror("fork()");
        exit(1);
    } 
    else if (pid == 0) 
        child(pipeIn, pipeOut);
    else 
        parent(pipeIn,pipeOut);

}

但是,此代码不起作用,因为我不断收到

dup2 pipeOut:未定义错误:0

它最终陷入僵局。
我知道代码停止是因为父母一直在等待孩子的回答(永远不会到达),而孩子也一直在等待永远不会到达的输入。

我不明白为什么我不断收到这个错误。难道我做错了什么?

我正在开发 MacOS Lion 10.7.2 和 Xcode 4.2.1。


更新:在亚当罗森菲尔德的回答之后,我更正了我的 if 语句。但是,正如我所说,代码仍然停止(我只能阅读孩子打印的第一件事,Child: Parent Message而没有其他内容)。

知道为什么会这样吗?

4

1 回答 1

2

dup2(2)成功时返回一个非负整数,即新的文件描述符。出错时返回 -1。在您的情况下,它在第一次调用时返回 0,因为您将管道复制到文件描述符 0 上。

要修复它,请将您的支票从 更改if(dup2(...))if(dup2(...) == -1)

于 2012-03-19T16:59:23.317 回答