The following program is a step toward how fork gets used in practice:
- Check this out (code is in lecture examples folder processes/separate.c and can also be viewed right here)
int main(int argc, char *argv[]) {
printf("Before.\n");
pid_t pid = fork();
exitIf(pid == -1, kForkFailed, stderr, "Fork function failed.\n");
printf("After.\n");
if (pid == 0) {
printf("I'm the child, and the parent will wait up for me.\n");
return 110; // contrived exit status
} else {
int status;
exitUnless(waitpid(pid, &status, 0) == pid, kWaitFailed, stderr,
"Parent's wait for child process with pid %d failed.\n", pid);
if (WIFEXITED(status)) {
printf("Child exited with status %d.\n", WEXITSTATUS(status));
} else {
printf("Child terminated abnormally.\n");
}
return 0;
}
}
- The above example directs the child process one way, the parent another.
- The parent process correctly waits for the child to complete, and this example (as opposed to the last example from the last slide deck) actually does the right thing by asserting waitpid's return value matches the process id of the child that exited.
- The parent also lifts exit status information about the child process out of the waitpid call, and uses the WIFEXITED macro to examine some high-order bits of this status argument to confirm the process exited normally, and it also uses the WEXITSTATUS macro to extract the lower eight bits from its argument to produce the child process's return value.
- Check out the man page for waitpid for the good word on all of the different macros. (Your textbook covers them all really nicely as well).