/* =============================================================================
 * 03_descriptors.c -- the three tables behind every descriptor
 * =============================================================================
 *
 * [Idea]
 *   A descriptor is not "the file". The kernel keeps THREE levels:
 *
 *     descriptor table        open file table              v-node table
 *     (one per PROCESS)       (one per OPEN, shared)       (one per FILE)
 *     fd 3 --------------->   { file POSITION, refcnt } --> { size, type, ... }
 *
 *   The middle level is the surprising one: the current file POSITION lives
 *   there, not in your process and not in the file. So:
 *     - opening the same file TWICE gives two open-file entries -> two INDEPENDENT
 *       positions;
 *     - fork() copies the descriptor TABLE but both tables point at the SAME
 *       open-file entry -> parent and child SHARE one position.
 *
 *   That shared position is why `prog1 >> log; prog2 >> log` interleave sensibly,
 *   and why a child's reads move the parent's file position. This demo proves
 *   both facts with real reads, using wait() so the output order is deterministic.
 *
 * [What it answers]
 *   - Where does the file position actually live?
 *   - Why do two open()s of one file not interfere, but a fork()ed child's reads do?
 *   - What does close() really do? (drop a reference, not necessarily the file)
 *
 * 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 "build/03_data.txt"

/* Read n bytes at the descriptor's CURRENT position and return them as a
 * NUL-terminated string in a static buffer (fine for this single-threaded demo). */
static const char *read_str(int fd, size_t n)
{
    static char buf[64];
    ssize_t got = rio_readn(fd, buf, n);
    if (got < 0) { perror("read"); exit(1); }
    buf[got] = '\0';
    return buf;
}

int main(void)
{
    /* Make a file with easily identified content: 0123456789abcdef... */
    const char *content = "0123456789ABCDEFGHIJ";
    int fd = open(PATH, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd < 0) { perror("open"); return 1; }
    rio_writen(fd, content, strlen(content));
    close(fd);
    printf("[setup] '%s' contains \"%s\"\n", PATH, content);

    /* ---- Experiment 1: TWO separate opens -> independent positions -------- */
    int fd1 = open(PATH, O_RDONLY);
    int fd2 = open(PATH, O_RDONLY);     /* a SECOND open of the same file */
    printf("\n[1] two separate open() calls: fd1=%d fd2=%d\n", fd1, fd2);
    printf("    fd1 reads 5 bytes: \"%s\"\n", read_str(fd1, 5));
    printf("    fd2 reads 5 bytes: \"%s\"   <-- starts at 0 again\n",
           read_str(fd2, 5));
    printf("    => two open-file entries, two INDEPENDENT positions\n");
    close(fd1);
    close(fd2);

    /* ---- Experiment 2: fork() -> a SHARED position ----------------------- */
    int shared = open(PATH, O_RDONLY);
    printf("\n[2] one open() then fork(): fd=%d in both processes\n", shared);

    /* [C tip] Flush BEFORE forking. When this demo's stdout is a pipe (as under
       `make run`) it is fully buffered, so everything printed so far is still in
       our buffer -- and fork() would copy it into the child, which would print
       it a second time. That is demo 05's lesson, met here for real. */
    fflush(stdout);

    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }
    if (pid == 0) {
        /* The child reads the first 5 bytes, then exits. */
        printf("    child  reads 5 bytes: \"%s\"\n", read_str(shared, 5));
        fflush(stdout);
        _exit(0);
    }
    waitpid(pid, NULL, 0);      /* wait -> the child's read definitely happened */

    /* The parent now reads. If the position were private it would read from 0
       and print "01234". If it is shared, it continues where the child stopped. */
    printf("    parent reads 5 bytes: \"%s\"   <-- continues after the child\n",
           read_str(shared, 5));
    off_t pos = lseek(shared, 0, SEEK_CUR);
    printf("    shared position is now %lld (not 5)\n", (long long)pos);
    printf("    => one open-file entry, refcount 2, ONE position\n");
    close(shared);

    /* ---- Experiment 3: what close() drops -------------------------------- */
    /* dup() makes a second descriptor pointing at the SAME open-file entry
       (refcount 2). Closing one leaves the other perfectly usable. */
    int a = open(PATH, O_RDONLY);
    int b = dup(a);
    printf("\n[3] dup(): fd %d and fd %d share one open-file entry\n", a, b);
    printf("    fd %d reads 3: \"%s\"\n", a, read_str(a, 3));
    printf("    fd %d reads 3: \"%s\"   <-- shared position, continues\n",
           b, read_str(b, 3));
    close(a);
    printf("    after close(%d), fd %d still reads 3: \"%s\"\n",
           a, b, read_str(b, 3));
    printf("    => close() drops a REFERENCE; the entry dies at refcount 0\n");
    close(b);

    printf("\nObservations\n------------\n");
    printf("- Two open()s of one file read the same bytes independently: the\n");
    printf("  position is per-OPEN, in the open file table.\n");
    printf("- After fork(), the child's read MOVED the parent's position (the\n");
    printf("  parent saw bytes 5-9, not 0-4): both descriptor tables point at\n");
    printf("  one open-file entry. This is how shell append-redirection shares\n");
    printf("  a file sensibly between parent and child.\n");
    printf("- dup() and fork() both add a reference, so close() on one copy is\n");
    printf("  harmless to the other -- the entry is freed only at refcount 0.\n");
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS):
 *   see the printed output; the key three facts are
 *     [1] fd1 "01234", fd2 "01234"   (independent positions)
 *     [2] child "01234", parent "56789", shared position 10   (ONE position)
 *     [3] dup'd descriptors share a position; close() is just an unref
 */
