|
simple (probably) pipe question
I'm new to programming with pipes, sockets, etc., and after seeing a particular code example that uses a pipe, I have a question. Here's the code example (which does the same as typing "ls | wc -l" at the command line):
int main(void)
{
int pfds[2];
pipe(pfds);
if (!fork()) {
close(1); /* close normal stdout */
dup(pfds[1]); /* make stdout same as pfds[1] */
close(pfds[0]); /* we don't need this */
execlp("ls", "ls", NULL);
} else {
close(0); /* close normal stdin */
dup(pfds[0]); /* make stdin same as pfds[0] */
close(pfds[1]); /* we don't need this */
execlp("wc", "wc", "-l", NULL);
}
return 0;
}
At first I was wondering what the file descriptor was after the 'dup' calls, but I guess that with the child, it would be stdout since 1 was just closed and 1 would be the next valid file descriptor in line (and similar with the parent). What I'm wondering about is that with the 'fork', there are now two processes running at the same time, and it seems like the output of this program wouldn't always be the same, that the child lines of code would have to run before the parent lines of code. Maybe someone could set me straight. Thank you.
|