Reputation: 38889
I've been wanting to create a child process that forks off twice to create two child processes. With the output of one, sent to the other. I found this example code. But I'm confused as to how it works.
I found an example here. But I'm confused by the way dup is used and how it works.
i.e.
close(1);
dup(fd[1]);
close(fd[0]);
close(fd[1]);
Output is then piped into a second forked process and it's pipes are connected like this:
close(0);
dup(fd[0]);
close(fd[0]);
close(fd[1]);
Upvotes: 0
Views: 2859
Reputation: 753605
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.
Upvotes: 2