The wait() System Call
This lesson will teach you about the `wait()` system call with the help of an example.
We'll cover the following
Running p2.c
So far, we haven’t done much: just created a child that prints out a message and exits. Sometimes, as it turns out, it is quite useful for a parent to wait for a child process to finish what it has been doing. This task is accomplished with the wait()
system call (or its more complete sibling waitpid()
); see the code below for details.
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/wait.h>int main(int argc, char* argv[]){printf("hello world (pid:%d)\n", (int)getpid());fflush(stdout);int rc = fork();if (rc < 0) { // fork failed; exitfprintf(stderr, "fork failed\n");exit(1);}else if (rc == 0) { // child (new process)printf("hello, I am child (pid:%d)\n", (int)getpid());}else { // parent goes down this path (main)int rc_wait = wait(NULL);printf("hello, I am parent of %d (rc_wait:%d) (pid:%d)\n", rc, rc_wait, (int)getpid());}return 0;}
In this example (p2.c
), the parent process calls wait()
to delay its execution until the child finishes executing. When the child is done, wait()
returns to the parent.
Adding a wait()
call to the code above makes the output deterministic. Can you see why? Go ahead, think about it.
(waiting for you to think … and done)
Now that you have thought a bit, let’s look at the output which might be similar to yours when you run p2.c
:
prompt> ./p2hello world (pid:29266)hello, I am child (pid:29267)hello, I am parent of 29267 (rc_wait:29267) (pid:29266)prompt>
With this code, we now know that the child will always print first. Why do we know that? Well, it might simply run first, as before, and thus print before the parent. However, if the parent does happen to run first, it will immediately call wait()
; this system call won’t return until the child has run and exited.
Thus, even when the parent runs first, it politely waits for the child to finish running, then wait()
returns, and then the parent prints its message.
Get hands-on with 1400+ tech skills courses.