The main relevant lines are these — they form a standard idiom (but it is easier to replace the first two lines with dup2(fd[1], 1)
):
close(1);
dup(fd[1]);
close(fd[0]);
close(fd[1]);
The dup()
function duplicates its argument file descriptor to the lowest-numbered unopen file descriptor. The close()
closes descriptor 1
, and descriptor 0
is still open, so the dup()
makes standard output 1
refer to the write side of the pipe fd[1]
. The other two close calls correctly close both ends of the pipe. The process shouldn't be reading from the read end of the pipe fd[0]
and standard output is writing to the write end of the pipe so the other descriptor isn't needed any more (and could lead to problems if it was not closed).
So, this is a standard sequence for connecting the write end of a pipe to the standard output of a process. The second sequence is similar, but connects the read end of the pipe to standard input (instead of the write end to standard output).
Generally, when you connect one end of a pipe to either standard input or standard output, the process should close both ends of the original pipe.
I note that there was no error checking, though it is unlikely that anything would go wrong — unless the process had been started with either standard output or standard input closed, contrary to all reasonable expectations.