Reap Zombie Children Automatically with SIGCHLD and SA_NOCLDWAIT
Stop zombie children in C on Linux with a SIGCHLD handler that loops on waitpid, or with SA_NOCLDWAIT, and learn what each choice costs you.

A server that forks a child per request cannot stop and wait for each one, and a server that never waits fills the process table with zombies. Two mechanisms solve this without blocking: a SIGCHLD handler that reaps every finished child, and the SA_NOCLDWAIT flag, which tells the kernel to discard the records itself. They look interchangeable and behave differently the moment you need an exit status. This post writes both in C against Linux 6.12 and glibc 2.40, and shows the bug that makes the handler version leak. For the background on zombies, see the post on zombie and orphan processes.
The behavior is specified in sigaction(2) and the POSIX sigaction page.
When SIGCHLD arrives
The kernel sends SIGCHLD to a parent when a child ends, and also when a child stops or resumes unless you ask otherwise. Its default action is to ignore the signal, which is why nothing visible happens when you forget to handle it: the zombies just accumulate. Installing a handler turns the signal into the cue to call waitpid.
A handler that reaps in a loop
The correct handler loops. Standard signals do not queue: if three children end while the handler is running or while SIGCHLD is blocked, the parent may be notified once. A handler that calls waitpid once reaps one child and leaves two.
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
static volatile sig_atomic_t reaped;
static void on_sigchld(int sig)
{
(void)sig;
int saved_errno = errno;
pid_t pid;
while ((pid = waitpid(-1, NULL, WNOHANG)) > 0)
reaped++;
errno = saved_errno;
}
int main(void)
{
struct sigaction sa = {0};
sa.sa_handler = on_sigchld;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_RESTART | SA_NOCLDSTOP;
if (sigaction(SIGCHLD, &sa, NULL) < 0) {
perror("sigaction");
return EXIT_FAILURE;
}
for (int i = 0; i < 5; i++) {
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0)
_exit(i);
}
sleep(1);
printf("reaped %d children\n", (int)reaped);
return EXIT_SUCCESS;
}All five children end at about the same moment, so the handler runs fewer than five times, but the loop collects every one of them:
reaped 5 childrenEach part of the handler has a reason. The WNOHANG flag stops the loop when no finished child remains. Saving and restoring errno keeps the handler from clobbering an error value the interrupted code was about to read. SA_RESTART makes slow system calls in the main program, such as read, resume instead of failing with EINTR. And SA_NOCLDSTOP stops the signal from firing when a child is merely stopped, which a handler that only wants to reap does not care about.
Inside a handler only async-signal-safe functions are allowed. waitpid is on that list, and printf is not, which is why the handler counts into a volatile sig_atomic_t and the main code prints.
The one-call handler bug
Change the loop to a single call and the program leaks:
static void on_sigchld_buggy(int sig)
{
(void)sig;
waitpid(-1, NULL, WNOHANG);
}With five children ending together, the output may be reaped 2 children or any number from 1 up. The remaining children stay zombies until another SIGCHLD arrives. The failure is intermittent, which makes it hard to find: with one child at a time it works every time. The cure is always the loop.
Letting the kernel discard the records
If you never need the exit status, you can skip the handler. Setting the SIGCHLD action to SIG_IGN, or installing a handler with SA_NOCLDWAIT, tells the kernel that this process does not want to wait for children, so children are removed when they end:
#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
struct sigaction sa = {0};
sa.sa_handler = SIG_DFL;
sigemptyset(&sa.sa_mask);
sa.sa_flags = SA_NOCLDWAIT;
if (sigaction(SIGCHLD, &sa, NULL) < 0) {
perror("sigaction");
return EXIT_FAILURE;
}
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0)
_exit(3);
sleep(1);
int status;
if (waitpid(pid, &status, 0) < 0)
printf("waitpid failed: %s\n", strerror(errno));
return EXIT_SUCCESS;
}After a second the child has ended and left no zombie, because the kernel threw the record away. The later waitpid finds nothing to collect:
waitpid failed: No child processThat error, ECHILD, is the price. Once you use SA_NOCLDWAIT or SIG_IGN, you cannot read an exit status or a resource usage from a child. On Linux, if you call wait while children are still running, it blocks until all of them have ended, and then fails with ECHILD. POSIX leaves some of this unspecified, so portable code should not depend on it.
Checking that nothing leaks
A leak test is easy to write and worth keeping. Start many short children, wait a moment, and count the zombies that remain under your own process. The count must be zero if the handler works. In a shell you can do the same check by hand while the program sleeps:
ps -o stat= --ppid "$(pgrep -n reap_handler)" | grep -c '^Z'0A result above zero means the reaping is incomplete, and the usual cause is the single-call handler from above or a signal blocked at the wrong moment. Run the check with a larger number of children, since the bug shows up only when several end close together. Raising the count from 5 to 500 in the example program turns a rare leak into a certain one, which is what you want from a test.
Choosing between them
| Need | Use |
|---|---|
| Fire-and-forget children, exit codes do not matter | SA_NOCLDWAIT or SIG_IGN |
| Log each child's exit code or signal | SIGCHLD handler with a waitpid loop |
| Restart a child that dies | handler that records the PID, main loop acts on it |
| Mix: reap some children, ignore others | handler, and let it reap everything, using the PID to tell them apart |
The second and third rows use the handler as a notification only. A common structure keeps the handler tiny, setting a flag or writing a byte to a pipe, and does the real work in the main loop, where all functions are safe to call. This is the self-pipe pattern, and it also fits poll loops that wait on sockets.
Blocking SIGCHLD around a wait
If your program calls waitpid for one specific child and also has the handler installed, the handler can run first and take the status. The call then fails with ECHILD. Block the signal around the section that creates and waits for that child:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
sigset_t block, old;
sigemptyset(&block);
sigaddset(&block, SIGCHLD);
sigprocmask(SIG_BLOCK, &block, &old);
pid_t pid = fork();
if (pid < 0) {
perror("fork");
return EXIT_FAILURE;
}
if (pid == 0) {
sigprocmask(SIG_SETMASK, &old, NULL);
_exit(9);
}
int status;
waitpid(pid, &status, 0);
printf("status %d\n", WEXITSTATUS(status));
sigprocmask(SIG_SETMASK, &old, NULL);
return EXIT_SUCCESS;
}status 9The child restores the mask before running its own code, since a blocked signal mask is inherited across fork. A pending SIGCHLD is delivered when the parent unblocks it, so a handler in the program still gets its turn for children it did not wait for.
Where signals are the wrong tool
A signal handler is a poor place to build a larger design. If your program already runs an event loop, a pidfd per child, or a signalfd for SIGCHLD, turns the notification into a readable descriptor, with no handler and no async-signal-safety rules. Libraries add a second reason for caution: a handler is process-wide, so a library that installs its own SIGCHLD handler replaces yours, and one that reaps with waitpid(-1, ...) can steal statuses your code wanted. If your program embeds other code, prefer waiting on specific child PIDs and leave SIGCHLD alone.


