1

管道的一种实现是:

#define STD_INPUT 0
#define STD_OUTPUT 1
pipeline(char *process1, char *process2)
{
    int fd[2];

    pipe(&fd[0]);
    if (fork() != 0) {
        /* The parent process executes these statements. */
        close(fd[0]);
        close(STD_OUTPUT);
        dup(fd[1]);
        close(fd[1]);    /* this file descriptor not needed anymore */
        execl(process1, process1, 0);
    }
    else {
        /* The child process executes these statements. */
        close(fd[1]);
        close(STD_INPUT);
        dup(fd[0]);
        close(fd[0]);   /* this file descriptor not needed anymore */
        execl(process2, process2, 0);
   }
}

我对分别使用每个 dup 调用之后的两个语句感到困惑。

close(fd[1]);    /* this file descriptor not needed anymore */

close(fd[0]);   /* this file descriptor not needed anymore */

我被告知不再需要描述符,但对我来说,这些描述符代表管道的每一端,那么为什么不再需要它们呢?

4

1 回答 1

4

pipe调用返回用于单向通信的读取描述符和写入描述符。但是,写入器不需要读取描述符 ( fd[0])。而且,读者不需要写描述符(fd[1])。因此,调用后的每个进程都会fork关闭它不需要的描述符,并使用它确实需要的描述符。

因此,父母是您示例中的作者。它fd[0]先关闭,然后关闭STD_OUTPUT。然后它会复制,因为它可用fd[1],它现在将在其中。STD_OUTPUT由于管道的输出描述符现在已复制,因此也不再需要它,因此将其关闭。现在,当作者向 写入内容时STD_OUTPUT,它将写入管道的输出描述符。

作为读者的孩子执行类似的逻辑,但在另一个描述符上。它首先关闭fd[1],然后关闭STD_INPUT。然后它会复制fd[0],从而导致描述符位于 中STD_INPUT。复制后,管道的输入描述符不再需要,因此关闭。现在,当阅读器从 中读取内容时STD_INPUT,它将从管道的输入描述符中读取。

于 2012-08-23T23:56:18.327 回答