/* =============================================================================
 * 05_buffering.c -- why printf and write come out in the wrong order
 * =============================================================================
 *
 * [Idea]
 *   printf does NOT write to the kernel. It appends to a buffer inside your
 *   process and hands the whole buffer to write() later -- when the buffer
 *   fills, when you print a '\n' to a terminal, when you call fflush(), or at
 *   exit(). write() has no buffer: it goes to the kernel immediately.
 *
 *   Mix the two on one descriptor and the output order follows the FLUSHES,
 *   not your source code. Two consequences bite everyone:
 *     (a) printf("A"); write(1,"B"); printf("C")  can come out as "BAC";
 *     (b) a buffer not flushed before fork() is COPIED, so its text prints TWICE.
 *
 *   Buffering also depends on the destination: stdout to a TERMINAL is
 *   line-buffered (flushed at each '\n'), but to a FILE or PIPE it is fully
 *   buffered (held until ~8 KB or exit). That is why a program's output can
 *   reorder the moment you redirect it -- the classic "it only breaks in the
 *   log file" bug. (This demo prints no '\n' in the test strings, so it behaves
 *   the same either way, and captures the result in a file to show you.)
 *
 * [What it answers]
 *   - Why does interleaving printf and write reorder the output?
 *   - Why can one printf appear twice after a fork?
 *   - What does fflush() actually do, and when must you call it?
 *
 * Build & run:    make run
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
#include "rio.h"

#define PATH_A "build/05_order.txt"
#define PATH_B "build/05_fork.txt"

/* Redirect stdout to `path`, returning a saved copy of the old stdout.
 * (The dup/dup2 technique of demo 04.) */
static int redirect_stdout(const char *path)
{
    fflush(stdout);                     /* never carry buffered text across */
    int saved = dup(STDOUT_FILENO);
    int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (saved < 0 || fd < 0) { perror("redirect"); exit(1); }
    dup2(fd, STDOUT_FILENO);
    close(fd);
    return saved;
}

static void restore_stdout(int saved)
{
    fflush(stdout);
    dup2(saved, STDOUT_FILENO);
    close(saved);
}

/* Read a whole small file into a static buffer as a C string. */
static const char *slurp(const char *path)
{
    static char buf[512];
    int fd = open(path, O_RDONLY);
    if (fd < 0) { perror("open"); exit(1); }
    ssize_t n = rio_readn(fd, buf, sizeof(buf) - 1);
    close(fd);
    buf[n > 0 ? n : 0] = '\0';
    return buf;
}

int main(void)
{
    /* ---- Surprise (a): printf vs write ordering -------------------------- */
    /* Source order is A, B, C. printf's A and C go to the stdio buffer; write's
       B goes straight to the kernel. Nothing is flushed until the end. */
    int saved = redirect_stdout(PATH_A);
        printf("A");                                /* buffered in the process */
        write(STDOUT_FILENO, "B", 1);               /* straight to the kernel  */
        printf("C");                                /* buffered               */
    restore_stdout(saved);                          /* fflush happens here     */

    const char *got = slurp(PATH_A);
    printf("[a] source order was printf(\"A\"), write(\"B\"), printf(\"C\")\n");
    printf("[a] the file actually contains: \"%s\"\n", got);
    printf("[a] => write() overtook both printfs, which waited in the buffer\n");

    /* ---- Surprise (b): an unflushed buffer survives fork() --------------- */
    /* printf("X") leaves X in the buffer. fork() copies the buffer into the
       child. Both processes later flush -> the single printf prints twice. */
    saved = redirect_stdout(PATH_B);
        printf("X");                    /* NOT flushed: still in our buffer */
        pid_t pid = fork();             /* the buffer is duplicated here     */
        if (pid == 0) {
            exit(0);                    /* [C tip] exit() FLUSHES stdio, so the
                                           child writes its copy of "X".
                                           _exit() would not -- that is the fix. */
        }
        waitpid(pid, NULL, 0);
    restore_stdout(saved);              /* the parent flushes its own "X"     */

    got = slurp(PATH_B);
    printf("\n[b] source had ONE printf(\"X\") before a fork()\n");
    printf("[b] the file actually contains: \"%s\"  (%zu characters)\n",
           got, strlen(got));
    printf("[b] => the unflushed buffer was copied; both processes flushed it\n");

    printf("\nObservations\n------------\n");
    printf("- printf is a LIBRARY call into a user-space buffer; write is a\n");
    printf("  SYSTEM call. Interleaving them scrambles the order (\"%s\" here).\n",
           slurp(PATH_A));
    printf("- fflush() before a write(), and before fork(), is the fix for both\n");
    printf("  surprises; in a child, _exit() avoids re-flushing inherited text.\n");
    printf("- Buffering depends on the destination: line-buffered to a terminal,\n");
    printf("  fully buffered to a file or pipe. So redirecting a program can\n");
    printf("  change its output ORDER without changing a line of its code.\n");
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS):
 *   [a] the file actually contains: "BAC"
 *   [b] the file actually contains: "XX"  (2 characters)
 *
 *   - "BAC", not "ABC": the raw write() reached the kernel while A and C were
 *     still in the stdio buffer, which was flushed afterwards.
 *   - "XX" from one printf: fork() duplicated the unflushed buffer and both
 *     processes flushed it at exit. Flushing before the fork prints one X.
 */
