Course contentsShow
← C
Lesson 1078 of 1,21915. Systems ProgrammingFree lesson

Preventing zombie processes

Preventing zombie processes

What you'll learn: How to use the wait() function to clean up finished child processes and keep your system's process table tidy.

The process that wouldn't leave

When a child process finishes its task and calls exit(), it doesn't vanish instantly. It enters a "zombie" state. In this state, the process is technically dead—it consumes no memory or CPU—but its entry remains in the system’s process table.

Think of a zombie process like a completed receipt at a restaurant. The meal is over, but the slip of paper stays on the table until the waiter (the parent process) picks it up. If the parent never "picks up the receipt," the table stays cluttered. If a program creates thousands of zombies, the system eventually runs out of process IDs (PIDs), preventing new programs from starting.

Performing the cleanup

To prevent zombies, the parent must acknowledge the child’s death. We do this using the wait() function. When a parent calls wait(), it pauses execution until one of its children finishes. Once the child exits, the operating system hands the child's exit status to the parent and finally deletes the child’s entry from the process table.

A clean execution

In this example, the parent explicitly waits for the child to finish, ensuring no zombies are left behind:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
    pid_t pid = fork();

    if (pid == 0) {
        // Child process
        printf("Child: I'm working for 2 seconds...\n");
        sleep(2);
        printf("Child: I'm done!\n");
        exit(0);
    } else {
        // Parent process
        printf("Parent: Waiting for my child to finish...\n");
        
        // wait(NULL) blocks the parent until the child exits
        // This "reaps" the child process, preventing a zombie
        wait(NULL); 
        
        printf("Parent: Child cleaned up. No zombies here!\n");
    }

    return 0;
}

If you removed the wait(NULL) line and told the parent to sleep(100), the child would remain a zombie for 100 seconds. By calling wait(), you fulfill your parental duty of "reaping" the child, allowing the operating system to fully release its resources.

Key takeaway

A zombie process is a dead child waiting for its parent to acknowledge its exit; always use wait() to collect exit statuses and clear the process table.