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.
The main relevant lines are these — they form a standard idiom (but it is easier to replace the first two lines with
close(1); dup(fd); close(fd); close(fd);
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. 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 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.
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.