I’m trying to implement unix piping in c (i.e. execute ls | wc). I have found a related solution to my problem (C Unix Pipes Example) however, I am not sure why a specific portion of the solved code snippet works.
Here’s the code:
/* Run WC. */
int filedes[2];
pipe(filedes);
/* Run LS. */
pid_t pid = fork();
if (pid == 0) {
/* Set stdout to the input side of the pipe, and run 'ls'. */
dup2(filedes[1], 1);
char *argv[] = {"ls", NULL};
execv("/bin/ls", argv);
} else {
/* Close the input side of the pipe, to prevent it staying open. */
close(filedes[1]);
}
/* Run WC. */
pid = fork();
if (pid == 0) {
dup2(filedes[0], 0);
char *argv[] = {"wc", NULL};
execv("/usr/bin/wc", argv);
}
In the child process that executes the wc command, though it attaches stndin to a file descriptor, it seems that we are not explicitly reading the output produced by ls in the first child process. Thus, to me it seems that ls is run independently and wc is running independently as we not explicitly using the output of ls when executing wc. How then does this code work (i.e. it executes ls | wc)?
The code shown just about works (it cuts a number of corners, but it works) because the forked children ensure that the the file descriptor that the executed process will write to (in the case of
ls) and read from (in the case ofwc) is the appropriate end of the pipe. You don’t have to do any more; standard input is file descriptor 0, sowcwith no (filename) arguments reads from standard input.lsalways writes to standard output, file descriptor 1, unless it is writing an error message.There are three processes in the code snippet; the parent process and two children, one from each
fork().The parent process should be closing both its ends of the pipe too; it only closes one.
In general, after you do a
dup()ordup2()call on a pipe file descriptor, you should close both ends of the pipe. You get away with it here becauselsgenerates data and terminates; you wouldn’t in all circumstances.The comment:
is inaccurate; you’re setting
stdoutto the output side of the pipe, not the input side.You should have an error exit after the
execv()calls; if they fail, they return, and the process can wreak havoc (for example, if thelsfails, you end up with two copies ofwcrunning.An SSCCE
Note the careful closing of both ends of the pipe in each of the processes. The parent process has no use for the pipe once it has launched both children. I left the code which closes
filedes[1]early in place (but removed it from an explicitelseblock since the following code was also only executed if theelsewas executed). I might well have kept pairs ofcloses()in each of the three code paths where files need to be closed.Example output: