Suppose I had the following code:
pid_t pid0, pid1;
pid0 = fork();
if (!pid0) {
pid1 = fork();
if (!pid1) { // p2
/* do something */
return;
} else { // p1
wait(NULL);
printf("p1 done\n");
return;
}
}
// p0
wait(NULL):
printf("p0 done\n");
Is the order of the print statements deterministic, or will it be up to the will of the CPU? In practice, it seems to be the same every time, but the docs for wait()
make it seem like it should be random.
EDIT: I've thought about it some more, and I'm wondering if it's always in that order because p0 doesn't have p2 as a child process; that's p1's child. So "p0 done" won't print until p1 finishes waiting for its child, p2. So, I suppose the real question is does wait()
wait for children's children, or just processes one "generation" away
Process 0 will always wait for process 1, because that's the only child it has. And process 1 will always wait for process 2, because that's the only child it has.
Process 0 won't return from wait
until process 1 exits, which means that process 1 has already printed its message, because it does that before it exits.
So in this case process 0 cannot continue until after the message has been printed.