管道的一种实现是:
#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 */
我被告知不再需要描述符,但对我来说,这些描述符代表管道的每一端,那么为什么不再需要它们呢?