wait
- C course
- Advanced
- Lesson 9/83
- 5 min
Learn to wait for processes with wait and waitpid.
The wait function
wait(&status) makes the parent wait for any child to finish. The child's exit status is written to the status variable.
You get the child's exit code with WEXITSTATUS(status). First check for normal exit with WIFEXITED(status): if true, the child ended with exit. Then WEXITSTATUS returns the value passed to exit. If it crashed with a signal, use WIFSIGNALED.
waitpid
waitpid(pid, &status, 0) waits for a specific child. You specify which child with pid; -1 means any.
The third parameter is options: 0 for normal wait, WNOHANG returns immediately without waiting. wait(&status) is actually a shortcut for waitpid(-1, &status, 0). With multiple children, you use waitpid to control which one you wait for.
Practice Capture the exit code
Create a process with pid_t pid = fork();. In the child, call exit(42);. In the parent, int status; wait(&status); and print the exit code with printf("%d\n", WEXITSTATUS(status));.
Starter code
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
// Fork, child exit(42)
// Parent wait
// Print WEXITSTATUS
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(void) {
pid_t pid = fork();
if (pid == 0) {
exit(42);
}
int status;
wait(&status);
printf("%d\n", WEXITSTATUS(status));
return 0;
}Expected output
42
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 wait call
int status;
wait(&____);
int status;
wait(&status);
Explanation: wait writes the exit status to the status variable.
2 Match wait macros
| Term | Meaning |
|---|---|
wait |
Any child |
waitpid |
Specific child |
WIFEXITED |
Normal exit? |
WEXITSTATUS |
Exit code |
3 What does WEXITSTATUS(status) return?
- The exit code Correct answer
- The signal number
- The PID
- The wait duration
Explanation: WEXITSTATUS returns the exit code passed to exit.