waitpid instructs a process to block until another process exits.
- The first argument specifies the wait set, which for the moment is just the id of the child process that needs to complete before waitpid can return. (There are more possibilities, but we'll explore them later).
- The second argument supplies the address of an integer where child termination status information can be placed (or we can pass in NULL if we don't care to get that information).
- The third argument is a collection of bit flags we'll study later. For the time being, we'll just go with 0 as the required parameter value, which means that waitpid should only return when a child exits.
- The return value is the id of the child process that exited, or -1 if waitpid was called and there were no child processes to wait on.
- Code for next small example is in lecture examples folder: processes/parent-child.c. Code is also right here.
- Here's that example:
static const int kForkFailure = 1;
int main(int argc, char *argv[]) {
printf("I'm unique and just get printed once.\n");
pid_t pid = fork(); // returns 0 within child, returns pid of child within fork
exitIf(pid == -1, kForkFailure, stderr, "Call to fork failed... aborting.\n");
bool parent = pid != 0;
if ((random() % 2 == 0) == parent) sleep(1); // force exactly one of the two to sleep
if (parent) waitpid(pid, NULL, 0); // parent shouldn't exit until it knows its child has finished
printf("I get printed twice (this one is being printed from the %s).\n", parent ? "parent" : "child");
return 0;
}
- The above example uses a coin flip to seduce one of the two processes to sleep for a second, which is normally all the time the other process needs to print what it needs to print first.
- The parent thread elects to wait for the child thread to exit before it allows itself to exit. It's a akin to a parent not being able to go to bed until he or she knows the child has, and it's emblematic of the types of synchronization directives we'll be seeing a lot of this quarter.
- Understand that the final printf gets executed twice. The child is always the first to execute it, however, because the parent is blocked in the waitpid call until the child executes everything.