In this lesson, you will learn why the SIGCHLD signal is the critical heartbeat that keeps your process tree clean of "zombie" debris.
The Zombie Problem
When a child process finishes execution, it doesn't immediately vanish from the system. It enters a "zombie" state (or defunct), where it occupies a slot in the system process table. It retains its Process ID (PID) and exit status so that the parent can eventually "reap" that information.
If the parent process is busy performing other tasks and fails to read this exit status, the zombie persists. A system cluttered with too many zombies will eventually run out of available PIDs, preventing you from starting new programs.
The Signal Solution: SIGCHLD
You shouldn't have to manually check for dead children in a loop—that would waste valuable CPU cycles. Instead, the Linux kernel uses asynchronous event handling.
Whenever a child process terminates, the kernel automatically sends a SIGCHLD signal to its parent. This signal acts as a notification: "One of your children has finished; come collect its exit status."
Implementing the Handler
By setting up a signal handler for SIGCHLD, a parent process can pause its own work only when a child actually dies. Inside this handler, the parent calls a wait function to reap the child:
// When SIGCHLD arrives, the handler triggers:
void sigchld_handler(int sig) {
// The parent reaps the child status
// preventing the zombie from persisting
wait(NULL);
}
By connecting the signal to a handler, you transform the parent from a "neglectful supervisor" into an "alert listener." The parent remains free to do its work, and the kernel guarantees that the parent is notified the moment a child process requires cleanup. This mechanism ensures that system resources are recycled immediately, maintaining the efficiency of your process tree.
Key Takeaway: The SIGCHLD signal is the essential callback mechanism that notifies a parent to reap terminated children, preventing process table exhaustion and zombie accumulation.