/* =============================================================================
 * 02_lost_signals.c -- why you cannot COUNT signals
 * =============================================================================
 *
 * [Idea]
 *   A signal is a one-bit fact: "a signal of type T is pending", yes or no.
 *   It is NOT a counter and NOT a queue. If a second SIGUSR1 arrives while one
 *   is already pending (not yet delivered), the second is simply dropped -- the
 *   pending bit is already set. So if a child sends the parent a million
 *   SIGUSR1s, the parent's handler runs FAR fewer than a million times.
 *
 *   This is the reason a SIGCHLD handler (demo 01) must reap in a loop rather
 *   than assume one signal per dead child: multiple deaths collapse into one
 *   delivery. Here we make the loss visible by sending many and counting how
 *   many actually arrive.
 *
 * [What it answers]
 *   - Do signals queue? (No -- at most one of each type can be pending.)
 *   - Why is "received" always far less than "sent" under a burst?
 *   - Why must handler logic be idempotent / drain state, never count events?
 *
 * Build & run:    make run
 *
 * Note: the exact "received" number varies run to run (it depends on the
 * scheduler); it is always MUCH less than SENT, and that gap is the point.
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <errno.h>

#define SENT 1000000L   /* how many signals the child fires at the parent */

static volatile sig_atomic_t received = 0;

static void usr1_handler(int sig)
{
    (void)sig;
    received++;          /* count how many SIGUSR1 deliveries actually happen */
}

int main(void)
{
    struct sigaction sa;
    sa.sa_handler = usr1_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;
    if (sigaction(SIGUSR1, &sa, NULL) < 0) { perror("sigaction"); return 1; }

    pid_t parent = getpid();
    printf("[parent] pid=%d; a child will send %ld SIGUSR1 signals\n",
           parent, SENT);
    fflush(stdout);

    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }

    if (pid == 0) {
        /* -------- child: fire a burst of signals at the parent -------- */
        for (long i = 0; i < SENT; i++)
            kill(parent, SIGUSR1);   /* each is a fast syscall; many will be
                                        merged because the parent cannot keep up */
        _exit(0);
    }

    /* -------- parent: reap the child, then report how many arrived -------- */
    int status;
    waitpid(pid, &status, 0);   /* signals keep arriving while we are blocked here */

    long got = (long)received;
    printf("[parent] sent %ld, received %ld  (%.4f%% delivered)\n",
           SENT, got, 100.0 * (double)got / (double)SENT);
    printf("[parent] the rest were MERGED: a pending SIGUSR1 cannot stack,\n"
           "         so a handler must never try to count signal events\n");
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS):
 *   [parent] pid=P; a child will send 1000000 SIGUSR1 signals
 *   [parent] sent 1000000, received ~85,000-91,000  (about 8-9% delivered)
 *   [parent] the rest were MERGED ...
 *
 *   - Only about one signal in twelve survives: while the parent handles one
 *     SIGUSR1, the many the child fires meanwhile all collapse into the single
 *     "pending" bit, so ~90% are lost. (The gap is even larger on a slower or
 *     busier machine; the ratio depends on how fast the parent drains them.)
 *   - The exact count changes every run (it is a race with the scheduler), but
 *     the vast majority are ALWAYS lost. Signals report that SOMETHING happened,
 *     never HOW MANY times -- the practical rule behind the demo-01 reaping loop.
 */
