This is essentially what the shell does if you build a redirect chain, i.e. something like
ls | grep foo | sort | uniq
In Unix programming, there are several excellent introduction texts in which a simple shell is implemented through the book. And one of the tasks of the shell is redirection. One of these books is Linux Application Programming by Michael C. Johnson and Eric W. Throne.
Book Homepage: http://ladweb.net/
To create a redirect chain for N processes, you will need N-1 pipes. For each redirection, you create a pipe using the pipe(int fds[2]) system call pipe(int fds[2]) . After fork() ing, but before execv ing, use dup2(int from, int to) to "connect" the end of the pipe to the standard input (0) or standard output of each process. Here's too simplified code without error checking:
int pipe_A[2]; int pipe_B[2]; pipe(pipe_A); pipe(pipe_B); pid_t pid_A, pid_B, pid_C; if( !(pid_A = fork()) ) { dup2(pipe_A[1], 1); execv(...); } if( !(pid_B = fork()) ) { dup2(pipe_A[0], 0); dup2(pipe_B[1], 1); execv(...); } if( !(pid_C = fork()) ) { dup2(pipe_B[0], 0); execv(...); }
Note that the pipe array indexes were chosen so that they reflect the standard file I / O descriptors if they are used to redirect stdio. This choice was not arbitrary.
Of course, you can connect pipes to any file descriptors (for example, there are some applications that expect their parent to open, say fd 3 and 4 connected to pipes), and most shells directly support this (for example, 1> & 3 will redirect stdout to fd 3). However, the array indices for pipe(int fds[2]) are 0 and 1, of course. I just talk about it because I had cultural programming students who thoughtlessly used target fds also for the syscall array for pipes.
To wait until all children finish using waitpid(-1, NULL, 0) , I think this meant -1 to my pre-responder, which means: wait until all the child processes are complete. Another option called wait() in a loop that returns the pid of the just finished child. If you call again and the child still works, he will be blocked again. If the child is left, he will return -1; I prefer waitpid solution.