Part 4 of 6 · 2 min read
SIGCHLD
In plain words: A server cannot sit in wait, since it has other work to do. Linux sends the parent SIGCHLD (page 6) whenever a child ends or stops. A handler for it can reap the child. The handler loops with waitpid(-1, ..., WNOHANG). The value -1 means any child, and WNOHANG makes the call return at once with 0 if no child has ended, instead of blocking. The loop is needed because several children that end together may produce only one signal (page 6, signals merge).
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/wait.h>
static volatile sig_atomic_t reaped = 0;
static void on_chld(int sig) {
(void)sig;
int saved = errno; /* keep errno safe for main */
while (waitpid(-1, NULL, WNOHANG) > 0) reaped++;
errno = saved;
}
int main(void) {
struct sigaction sa; memset(&sa, 0, sizeof sa);
sa.sa_handler = on_chld; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART;
sigaction(SIGCHLD, &sa, NULL);
for (int i = 0; i < 5; i++) if (fork() == 0) _exit(0);
sleep(1);
printf("children reaped by handler: %d\n", (int)reaped);
char cmd[64]; snprintf(cmd, sizeof cmd, "ps --ppid %d -o stat= | grep -c Z", (int)getpid());
fflush(stdout);
if (system(cmd) < 0) return 1;
return 0;
}
children reaped by handler: 5
0
All five children were reaped by the handler, and the count of zombies is 0. The flag SA_RESTART asks the kernel to restart slow system calls, such as read, that the signal interrupted, so the program does not have to handle EINTR (page 6) everywhere. Saving and restoring errno is the small habit that keeps the handler from disturbing a call that was in progress in the main program.
Read it as
Every process that creates children owes the system one wait per child. Either call it yourself, or let a SIGCHLD handler do it.
Check yourself:
1. What does WNOHANG do?
2. Why does the handler loop?
3. Why does the handler save errno?