When using fork(), is it possible to ensure that the child process executes before the parent without using wait() in the parent?
This is related to a homework problem in the Process API chapter of Operating Systems: Three Easy Pieces, a free online operating systems book.
The problem says:
- Write another program using
fork(). The child process should print "hello"; the parent process should print "goodbye". You should try to ensure that the child process always prints first; can you do this without callingwait()in the parent?
Here's my solution using wait():
#include <stdio.h>
#include <stdlib.h> // exit
#include <sys/wait.h> // wait
#include <unistd.h> // fork
int main(void) {
int f = fork();
if (f < 0) { // fork failed
fprintf(stderr, "fork failed\n");
exit(1);
} else if (f == 0) { // child
printf("hello\n");
} else { // parent
wait(NULL);
printf("goodbye\n");
}
}
After thinking about it, I decided the answer to the last question was "no, you can't", but then a later question seems to imply that you can:
- Now write a program that uses
wait()to wait for the child process to finish in the parent. What doeswait()return? What happens if you usewait()in the child?
Am I interpreting the second question wrong? If not, how do you do what the first question asks? How can I make the child print first without using wait() in the parent?
waitpid(), orwaitid()(or, on some systems,wait3()orwait4()) count as 'not callingwait()'? How inventive do you want to get? (You could open a pipe, close the write end, and execute a read on the read end; when the child exits, the write end of the pipe will be closed, so the parent will get EOF — 0 bytes read — and it knows that the child died, and all its children, etc. That's not completely foolproof, but it depends on the context; do you know what the child processes will be doing?)printfis not enough to guarantee that the data is written). Or have the parent wait for some event in the filesystem which the child triggers. (eg, parent tries to open a fifo, which will block until the child opens the fifo, but this is fundamentally the same as blocking on a read)SIGCHLDdoesn't count, even though thesiginfo_thas a lot of useful info.WNOWAITflag can often be used when you want to preservewaitability.