/* =============================================================================
 * 01_sigchld_reaper.c -- the correct way to reap children: a SIGCHLD handler
 * =============================================================================
 *
 * [Idea]
 *   A server forks worker children and must reap each one (Lecture 16) without
 *   blocking its main loop in wait(). The kernel helps: when a child dies it
 *   sends the parent a SIGCHLD signal. So the parent installs a SIGCHLD handler
 *   that reaps whatever is ready and returns.
 *
 *   The trap this demo teaches: signals DO NOT QUEUE. If three children die at
 *   nearly the same time, the parent may receive only ONE SIGCHLD, because a
 *   second signal of a type already pending is merged into the first. A handler
 *   that reaps exactly one child would therefore leak zombies. The correct
 *   handler reaps in a LOOP with waitpid(..., WNOHANG) until none are left.
 *
 * [What it answers]
 *   - How does a parent reap children asynchronously, off the main loop?
 *   - Why must a SIGCHLD handler loop instead of reaping one child?
 *   - What does WNOHANG do, and why sig_atomic_t for the counter?
 *
 * Build & run:    make run
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>

#define N 5     /* number of worker children */

/* [C tip] A variable shared between a handler and main must be
   `volatile sig_atomic_t`: `volatile` stops the compiler caching it in a
   register (the handler changes it "behind main's back"), and sig_atomic_t is
   a type the platform guarantees is read/written in one uninterruptible step. */
static volatile sig_atomic_t reaped = 0;

/* The handler. It is entered on SIGCHLD and reaps EVERY child that is ready,
   because several deaths may be collapsed into one delivered signal. */
static void sigchld_handler(int sig)
{
    (void)sig;
    int saved_errno = errno;   /* [C tip] a handler must restore errno: it runs
                                  "between" the main code's instructions and
                                  must not clobber the errno main was about to read. */
    pid_t pid;
    /* WNOHANG: return 0 immediately if no dead child is waiting, instead of
       blocking. Loop until waitpid says "none ready" (0) or "no children" (-1). */
    while ((pid = waitpid(-1, NULL, WNOHANG)) > 0)
        reaped++;              /* async-signal-safe: just a counter bump */
    errno = saved_errno;
}

int main(void)
{
    /* Install the handler with sigaction (the portable, well-defined way).
       SA_RESTART asks the kernel to restart interrupted system calls where it
       can, so our main-loop sleep is not torn apart by every delivery. */
    struct sigaction sa;
    sa.sa_handler = sigchld_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGCHLD, &sa, NULL) < 0) { perror("sigaction"); return 1; }

    printf("[parent] pid=%d forking %d children\n", getpid(), N);
    fflush(stdout);

    for (int i = 0; i < N; i++) {
        pid_t pid = fork();
        if (pid < 0) { perror("fork"); return 1; }
        if (pid == 0) {
            /* children all exit at roughly the same moment, so their SIGCHLDs
               pile up -- the exact situation that merges signals. */
            _exit(0);
        }
    }

    /* Main "loop": wait until all children have been reaped by the handler.
       We sleep in small slices; each SIGCHLD wakes us, the handler reaps, and
       we re-check the count. (A real server would do its work here instead.) */
    while (reaped < N)
        usleep(10 * 1000);     /* 10 ms slices; handler does the real work */

    printf("[parent] handler reaped %d children; none leaked as zombies\n",
           (int)reaped);
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS):
 *   [parent] pid=P forking 5 children
 *   [parent] handler reaped 5 children; none leaked as zombies
 *
 *   - All 5 children were reaped even though the 5 SIGCHLDs may have been
 *     delivered as FEWER than 5 signals: the while/WNOHANG loop drains every
 *     ready child per delivery. A reap-exactly-one handler would have leaked
 *     zombies here -- the central lesson.
 *   - The counter is `volatile sig_atomic_t` and the handler restores errno:
 *     the two rules that keep a handler from corrupting the main program.
 */
