Waiting for children with wait()
What you'll learn: How to use the wait() system call to synchronize a parent process with its child and prevent "zombie" processes.
The Parent's Responsibility
In Linux systems, when a parent process creates a child using fork(), they become two independent travelers running at their own pace. However, the parent has a final duty: it must acknowledge the child's completion.
If a child finishes its task while the parent is still busy, the child doesn't fully disappear. It enters a "Zombie" state. It’s dead, but it still occupies an entry in the system’s process table. To clean up this mess and collect the child’s exit status, the parent must call wait().
Think of wait() like a school bus driver. The driver (parent) cannot leave the parking lot until they confirm the student (child) has finished their after-school club. If the student is still inside, the driver sits and waits.
How wait() works
The wait() function does two things:
- It blocks the parent. The parent pauses execution until one of its children terminates.
- It reaps the child. It cleans up the zombie and retrieves the child's exit code.
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// The Child process
printf("Child: I'm doing some work for 2 seconds...\n");
sleep(2);
printf("Child: I'm done!\n");
} else {
// The Parent process
printf("Parent: I'm waiting for my child to finish.\n");
// This line pauses the parent until the child exits
wait(NULL);
printf("Parent: My child has exited. Now I can finish too.\n");
}
return 0;
}
Why it matters
Without wait(), your system could eventually fill up with zombie processes, which is a form of resource leak. Additionally, using wait() ensures an orderly flow. If your parent process needs a file that the child is currently writing, wait() ensures the parent doesn't try to open that file until the child is officially finished.
Key takeaway
The wait() system call pauses the parent process until a child finishes, ensuring proper cleanup and process synchronization.