/* =============================================================================
 * 03_reaper.c -- creating children, and cleaning them up (reaping)
 * =============================================================================
 *
 * [Idea]
 *   A process that exits does NOT vanish. It becomes a "zombie": dead, running
 *   nothing, but still holding a slot in the kernel's process table so that its
 *   parent can read HOW it died (its exit status). The parent collects that
 *   status with wait()/waitpid(); doing so is called REAPING and it frees the
 *   zombie's slot. A parent that never reaps leaks process-table slots.
 *
 *   This program forks N children, each exiting with a distinct status, then
 *   reaps them one at a time with waitpid() and reports what it learned about
 *   each. Watch: the children finish in an UNPREDICTABLE order (they race), so
 *   we collect their results and SORT by child id before printing, to get a
 *   stable, readable report out of a nondeterministic schedule.
 *
 * [What it answers]
 *   - How does a parent learn a child's exit status, and in what order?
 *   - What is a zombie, and what makes it go away?
 *   - How do the WIFEXITED / WEXITSTATUS macros decode wait()'s status word?
 *
 * Build & run:    make run
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

#define N 5     /* how many children to create */

int main(void)
{
    printf("[parent] pid=%d creating %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) {
            /* child i: exit with status 10+i so each is distinguishable.
               A tiny, i-dependent sleep makes the finishing order vary. */
            usleep((N - i) * 1000);   /* later children finish sooner */
            _exit(10 + i);
        }
        /* parent keeps looping to create the next child */
    }

    /* Reap all N children. waitpid(-1, ...) waits for ANY child; it returns
       them in whatever order they happen to finish. We record (pid, status)
       and sort afterward so the printed table is deterministic. */
    pid_t pids[N];
    int   codes[N];
    int   reaped = 0;
    int   status;
    pid_t w;
    while ((w = waitpid(-1, &status, 0)) > 0) {
        pids[reaped]  = w;
        /* WIFEXITED: did the child exit normally (vs killed by a signal)?
           WEXITSTATUS: the low 8 bits it passed to _exit(). */
        codes[reaped] = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
        reaped++;
    }
    /* simple insertion sort by pid for a stable report */
    for (int i = 1; i < reaped; i++) {
        pid_t pk = pids[i]; int ck = codes[i]; int j = i - 1;
        while (j >= 0 && pids[j] > pk) { pids[j+1]=pids[j]; codes[j+1]=codes[j]; j--; }
        pids[j+1] = pk; codes[j+1] = ck;
    }

    printf("[parent] reaped %d children (sorted by pid):\n", reaped);
    for (int i = 0; i < reaped; i++)
        printf("           child pid=%d exited with status %d\n", pids[i], codes[i]);

    printf("[parent] all children reaped; no zombies remain\n");
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS):
 *   [parent] pid=P creating 5 children...
 *   [parent] reaped 5 children (sorted by pid):
 *              child pid=.. exited with status 10
 *              child pid=.. exited with status 11
 *              ... status 12, 13, 14
 *   [parent] all children reaped; no zombies remain
 *
 *   - waitpid(-1,...) handed the children back in FINISH order, not creation
 *     order; sorting by pid gives the stable table above. The exit statuses
 *     (10..14) are each decoded correctly by WEXITSTATUS.
 *   - When waitpid returns <= 0 the loop stops: there are no more children to
 *     reap. Every zombie slot has been freed.
 */
