One implementation of a pipe is:
#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);
}
}
I am confused by the use of the two statements which follow each dup call, respectively.
close(fd[1]); /* this file descriptor not needed anymore */
and
close(fd[0]); /* this file descriptor not needed anymore */
I am told the descriptors are no longer needed, but to me those descriptors represent each end of the pipe, so why are they no longer needed?
The
pipecall returns both the read descriptor and the write descriptor for unidirectional communication. However, the writer does not need the read descriptor (fd[0]). And, the reader does not need the write descriptor (fd[1]). So, each process after theforkcall closes the descriptor it does not need, and uses the descriptor that it does need.So, the parent is the writer in your example. It closes the
fd[0]first, and then closesSTD_OUTPUT. It then duplicatesfd[1], which will now be inSTD_OUTPUTsince it is available. Since the output descriptor of the pipe is now duplicated, it is no longer needed either, so it is closed. Now, when the writer writes something toSTD_OUTPUT, it will be writing to the output descriptor of the pipe.The child, which is the reader, performs similar logic, but on the other descriptor. It first closes
fd[1], and then closesSTD_INPUT. It then duplicatesfd[0], which results in the descriptor being inSTD_INPUT. After being duplicated, the input descriptor of the the pipe is no longer needed, so it is closed. Now, when the reader reads something fromSTD_INPUT, it will be reading from the input descriptor of the pipe.