Course contentsShow
← Computer Science
Lesson 1227 of 2,87228. Operating Systems FundamentalsFree lesson

Process Waiting: wait() and waitpid()

Understand how parents wait for children and retrieve their exit status.

Process Waiting: wait() and waitpid()

What You'll Learn

You'll learn how parent processes can wait for their child processes to finish and retrieve the exit status they return.


Why Parents Need to Wait

Remember from previous lessons that fork() creates a parent-child process relationship, and children eventually terminate with exit(). But what happens to that exit status the child returned? The parent needs a way to collect it—otherwise, the child becomes a zombie process (still in the process table but not running).

The wait() and waitpid() system calls solve this problem by letting the parent pause and retrieve the child's exit status.


The wait() System Call

wait() blocks the parent process until any of its children terminates. It returns the process ID of the terminated child and stores the exit status in a variable you provide.

Example scenario:

  • Parent forks a child
  • Child does some work and calls exit(5)
  • Parent calls wait() and pauses
  • When child terminates, wait() returns with the child's PID and exit code 5
  • Parent can now continue, knowing the child finished

The waitpid() System Call

waitpid() is more flexible—it lets you wait for a specific child by PID, or control whether to block or return immediately. You can also wait for any child (like wait()) or wait for children in a process group.

Key difference: wait() is simpler but less flexible; waitpid() gives you precise control over which child to wait for and how to wait.


Key Takeaway:
wait() and waitpid() allow parent processes to synchronize with their children, retrieve exit statuses, and prevent zombie processes by cleaning up terminated child process entries.