/* =============================================================================
 * 01_process_server.c -- a concurrent server: one PROCESS per client
 * =============================================================================
 *
 * [Idea]
 *   Lecture 20's echo server served one client to completion before accepting
 *   the next. One slow client therefore blocked everyone. The simplest fix uses
 *   machinery you already have (Lecture 16): after accept(), FORK. The child
 *   serves that one client and exits; the parent immediately loops back to
 *   accept the next. Clients are then served concurrently, by separate
 *   processes, with no shared state to corrupt.
 *
 *   Two details are easy to get wrong, and both come from Lecture 16-17:
 *     1. DESCRIPTORS ARE SHARED by fork. The child must close the LISTENING
 *        descriptor and the parent must close the CONNECTED one -- otherwise
 *        each connection leaks a descriptor in the other process, and the
 *        client never sees EOF because a copy of its socket stays open.
 *     2. CHILDREN MUST BE REAPED, or they pile up as zombies. The parent is
 *        busy in accept(), so reaping happens asynchronously in a SIGCHLD
 *        handler -- with the WNOHANG loop of Lecture 17, because several
 *        children can die between deliveries.
 *
 * [What it answers]
 *   - How do you make a server concurrent with only fork()?
 *   - Which descriptors must each side close, and what breaks if you forget?
 *   - Why does this server need a SIGCHLD handler at all?
 *
 * Usage:   ./01_process_server [port] [max_connections]
 *          defaults: 15221, 8
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include "netutil.h"
#include "rio.h"

#define MAXLINE 8192

static volatile sig_atomic_t reaped = 0;

/* Lecture 17's correct handler: drain EVERY ready child, save/restore errno. */
static void sigchld_handler(int sig)
{
    (void)sig;
    int saved = errno;
    while (waitpid(-1, NULL, WNOHANG) > 0)
        reaped++;
    errno = saved;
}

/* Serve one client to completion, then return. Runs in the CHILD. */
static void echo_loop(int connfd)
{
    rio_t rio;
    char  buf[MAXLINE];
    rio_readinitb(&rio, connfd);
    ssize_t n;
    while ((n = rio_readlineb(&rio, buf, MAXLINE)) > 0)
        rio_writen(connfd, buf, (size_t)n);
}

int main(int argc, char **argv)
{
    const char *port = (argc > 1) ? argv[1] : "15221";
    int maxconn      = (argc > 2) ? atoi(argv[2]) : 8;

    struct sigaction sa;
    sa.sa_handler = sigchld_handler;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = SA_RESTART;       /* [Systems link] without SA_RESTART, a
                                       SIGCHLD arriving during accept() makes it
                                       fail with EINTR -- see the check below. */
    if (sigaction(SIGCHLD, &sa, NULL) < 0) { perror("sigaction"); return 1; }

    int listenfd = open_listenfd(port);
    if (listenfd < 0) { fprintf(stderr, "cannot listen on %s\n", port); return 1; }
    printf("[process-server] listening on 127.0.0.1:%s, serving up to %d clients\n",
           port, maxconn);
    fflush(stdout);

    for (int i = 0; i < maxconn; i++) {
        int connfd = accept(listenfd, NULL, NULL);
        if (connfd < 0) {
            if (errno == EINTR)
                continue;           /* a signal interrupted accept: retry */
            perror("accept");
            break;
        }

        pid_t pid = fork();
        if (pid < 0) { perror("fork"); close(connfd); continue; }

        if (pid == 0) {
            /* ---- CHILD: serve this one client ---- */
            close(listenfd);        /* (1) the child has no use for the queue */
            echo_loop(connfd);
            close(connfd);
            _exit(0);               /* _exit: do not flush the parent's buffers */
        }

        /* ---- PARENT: hand the connection off and move on ---- */
        close(connfd);              /* (1) CRITICAL: the child owns it now. If
                                       the parent keeps a copy open, the socket
                                       is never fully closed and the client
                                       waits forever for EOF. */
        printf("[process-server] client %d -> child pid %d\n", i + 1, pid);
        fflush(stdout);
    }

    /* Wait for any children still serving, so the demo ends tidily. */
    while (waitpid(-1, NULL, 0) > 0)
        reaped++;

    close(listenfd);
    printf("[process-server] done; %d child(ren) reaped\n", (int)reaped);

    printf("\nObservations\n------------\n");
    printf("- Each client was served by its OWN process, so a slow client could\n");
    printf("  not block the others: the parent returned to accept() at once.\n");
    printf("- fork() shares DESCRIPTORS: the child closes listenfd, the parent\n");
    printf("  closes connfd. Forgetting the parent's close() is the classic bug\n");
    printf("  -- the connection stays half-open and the client hangs at EOF.\n");
    printf("- Children are reaped asynchronously by a SIGCHLD handler with a\n");
    printf("  WNOHANG loop (Lecture 17), because the parent is blocked in\n");
    printf("  accept() and several children may die between deliveries.\n");
    printf("- Cost: a whole process (page tables, descriptors) per client, and\n");
    printf("  sharing data between clients needs real IPC. Threads (demo 03)\n");
    printf("  are cheaper and share memory -- for better and for worse.\n");
    return 0;
}
