Files
42-exam06/fundamentals.md
T

12 KiB

Fundamentals — the 9 ideas behind mini_serv

You said it: it's time to understand, not just replay. This file explains the 9 ideas the exam is built out of. Each idea ends with a tiny experiment (in explore/) that lets you see it. Do them in order — total ~45 minutes with the experiments.

Everything here assumes Linux (like the 42 exam sessions).


1. Everything is a file number (fd)

The kernel gives every process a table of open resources. The fd (file descriptor) is the index into that table — just a small integer. It doesn't matter if the "file" is a real file, a pipe, the terminal, or a socket: same namespace, same read/write/close.

fd Normally
0 stdin (your terminal input)
1 stdout (terminal output)
2 stderr (always write error messages here: write(2, ...))
3+ everything the program opens: files, sockets, …

Two consequences the exam cares about:

  • the kernel always reuses the smallest free number, so fds get recycled after close();
  • close(fd) and then using that fd anyway = undefined behavior (usually "Bad file descriptor").

Experiment 01 (explore/01_fds.c): prints fd numbers of a file and a socket, then closes them and opens again — watch the numbers get reused.

2. A socket is an fd that talks to the network

int fd = socket(AF_INET, SOCK_STREAM, 0); asks the kernel for a network endpoint:

  • AF_INET — IPv4 (the exam uses only IPv4 and only 127.0.0.1);
  • SOCK_STREAM — TCP: connection-oriented, reliable, ordered byte stream;
  • returns an fd, or -1 on failure.

A socket is one end of a connection. TCP connections have two ends living in two processes (maybe on different machines). Yours talks to the kernel on this side and the kernel talks to the peer's kernel. You never see packets — you see bytes in, bytes out.

flowchart LR
    A["your process (mini_serv)<br/>fd 3 = listening socket<br/>fd 4, 5 = client sockets"] -->|"syscalls on fd numbers"| K["kernel<br/>socket objects with send/recv buffers"]
    K <-->|"TCP byte stream (loopback here)"| B["the other process (nc, or the grader)<br/>its own fd table, its own socket"]

3. Addresses, ports and byte order

To be reachable, a TCP endpoint needs an address: IP : port.

struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));          /* zero first — garbage fields break bind */
addr.sin_family = AF_INET;               /* IPv4 */
addr.sin_addr.s_addr = htonl(2130706433);/* 127.0.0.1, in network byte order */
addr.sin_port = htons(atoi(argv[1]));    /* port from argv, network byte order */
  • Ports are 16-bit; your program gets one as text ("8081") → atoi turns it into a number.
  • Byte order: x86 stores numbers little-endian; the network protocol is big-endian. htons = host-to-network-short (16 bit, ports), htonl = host-to-network-long (32 bit, IPs). Forget them and you bind to a bizarre address.
  • 2130706433 = 0x7F000001 = the four bytes 127.0.0.1. The subject demands you listen only on localhost, so this magic number is your friend. (INADDR_ANY would listen on every interface — wrong for this exam.)

4. Server lifecycle: socket → bind → listen → accept

Call Meaning Analogy
socket() create an endpoint buy a phone
bind() attach address+port to it get a phone number
listen() mark it as "accepting connections", with a backlog open the shop, queue callers
accept() take one pending connection out of the queue; returns a NEW fd answer one call

The critical insight: the listening fd keeps listening forever; accept() returns a different fd — the fd of that one conversation. The exam server has: 1 listening fd + 1 fd per connected client.

flowchart LR
    C1["client connect()"] --> Q
    C2["client connect()"] --> Q
    Q["accept queue (backlog 10)<br/>the kernel finishes each TCP handshake<br/>and parks the connection here"]
    L["listening fd"] --> Q
    Q -- "accept() pops ONE connection" --> S["your program gets a NEW fd for it<br/>(the listening fd keeps listening)"]

Experiment 02 (explore/02_bind_listen.c): binds and listens but deliberately never calls accept(). Run it, then:

ss -tlnp | grep PORT          # your LISTEN socket, backlog visible
nc -v 127.0.0.1 PORT          # the TCP handshake COMPLETES anyway!
ss -tnp | grep PORT           # the connection sits ESTABLISHED in the accept queue

This shows why "nc connects" ≠ "my program accepted it", and what "backlog" means: the kernel accepts handshakes for you and queues them until your program calls accept().

5. TCP is a byte stream, not messages

This one is the exam. There are no message boundaries on a TCP connection. If the peer writes "hello\nworld\n", then in your process:

  • the first recv() may return "hello\nworld\n" (both lines),
  • or "hel", then "lo\nworld\n",
  • or "hello\nw", then "orld\n",
  • anything — the split is decided by the kernel, network timing, buffering… not by you.

Also: your recv() returns up to what you asked (sizeof buf) and waits if there's nothing available (unless the fd is non-blocking). The exam's rule is: only call recv after select said that fd is readable, and never assume a full line arrived.

Real servers therefore keep a buffer per client (clients[fd].msg in your friend's code) and split complete lines out of it: that's exactly str_join + extract_message.

sequenceDiagram
    participant W as sender writes
    participant K as kernel buffers
    participant R as your recv calls
    W->>K: "hello\nworld\n" (one write)
    K-->>R: recv gives "hel"
    R->>R: buffer = "hel"
    K-->>R: recv gives "lo\nwor"
    R->>R: buffer = "hello\nwor" then extract "hello\n"
    K-->>R: recv gives "ld\n"
    R->>R: buffer = "wor" + "ld\n" then extract "world\n"
    Note over R: one write, three chunks, lines rebuilt — never assume the split

Experiment 03 (explore/03_accept_recv.c): accepts one client and prints each recv() with its exact size. Then in another terminal:

nc 127.0.0.1 PORT      # type "hello" + Enter slowly, then fast, and watch the chunking

and try the scripted split (sends "par", waits 1s, sends "tial\n" on the same connection):

send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
{ printf 'par'; sleep 1; printf 'tial\n'; } | send PORT

You'll see two recv events for one logical line — THAT is why the buffer exists.

6. EOF: recv() returns 0

How do you learn the peer is gone? recv() tells you by returning:

return meaning
> 0 that many bytes arrived
0 EOF — the peer closed/shutdown its writing side (orderly close)
-1 error (connection reset, bad fd, …)

In the exam: recv() <= 0 → broadcast "server: client N just left\n", close(fd), free the buffer. Nothing else. The leftover partial line is not flushed.

On a live nc, press Ctrl-C (process dies → kernel sends FIN → your recv returns 0), or use nc -N which closes the socket when its stdin hits EOF.

7. select() — the waiting room

Without select you'd need one thread per client (allowed? complicated) or blocking reads in a loop (you'd stall on the first idle client). select solves "wait for any of N fds":

fd_set readfds;
FD_ZERO(&readfds);                 /* empty the set (bitmap of fds) */
FD_SET(3, &readfds);               /* add fd 3 */
FD_SET(listen_fd, &readfds);       /* add the listener */
select(max_fd + 1, &readfds, NULL, NULL, NULL);
/* returns when >= 1 fd in the set is readable */
if (FD_ISSET(3, &readfds)) { /* fd 3 has data (or EOF) */ }
flowchart TD
    A["FD_ZERO + FD_SET: rebuild the watch list"] --> B["select: sleep until at least one fd is ready"]
    B --> C["FD_ISSET(fd): which one(s)?"]
    C --> D["handle it, then loop back and rebuild"]
    D --> A
Macro / rule Meaning
FD_ZERO clear all bits
FD_SET(fd, &set) mark one fd
FD_CLR(fd, &set) unmark (do this when a client leaves!)
FD_ISSET(fd, &set) was that fd ready?
nfds = max_fd + 1 "watch fds 0..max_fd"
timeout NULL block forever until something is ready

Two traps that decide the exam:

  1. select is destructive. It rewrites the sets to contain only the ready fds. Next iteration you must start from a fresh/master set (that's what active_fds is for in your friend's code, or the rebuild-from-array approach in reference/mini_serv.c).
  2. max_fd must be correct. If the newest client is fd 7 but you pass 6+1, that client can pile up data unnoticed.

Why select instead of poll? The subject's allowed list has select. That's the reason.

Experiment 04 (explore/04_select_two.c): selects on stdin and a listening socket at once: type in the terminal → "stdin ready"; run nc → "listener ready". You are literally watching the waiting room.

8. What "readable" means per socket type

Socket "readable" means your reaction
listening fd a new connection is waiting in the accept queue accept()
client fd bytes arrived or EOF is pending recv(); if it returns <= 0 → disconnect

select also can report writable — and a connected TCP socket is almost always writable (the kernel's send buffer has room). That's why the friend's code can use write_fds as a cheap "who's still connected" list, and why waiting for writability is not useful here.

9. The little world your server keeps

     listening fd ── select() says readable ──► accept() ──► new client fd
                                                                 │
      for each client fd:                                        ▼
        clients[fd].id    the announced number (0,1,2,… forever, never reused)
        clients[fd].msg   pending partial line (append with str_join, mine lines with
                          extract_message, free it on disconnect)

     ids ≠ fds: fd = kernel's slot number (recycled), id = your counter (monotonic).

Ownership in one line: whoever sees a malloc (or receives a char *) frees it. str_join frees the old buffer; the message extract_message gives you is yours to free; the leftover buffer dies with the client; the relay string you build dies right after send.


10. How to test each part of YOUR mini_serv

Paste this helper in a terminal once (it's the same trick the grader uses):

send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }

Then, from the repo root (./sandbox/mini_serv 8081 running in another terminal):

Part of your code Test Expected observation
argc guard ./mini_serv; echo $? Wrong number of arguments on stderr, exit 1
bind/listen ss -tlnp | grep 8081 a LISTEN line, plus the process name
select loop idle sanity top -p $(pgrep mini_serv) ~0% CPU when nobody is connected (100% = set rebuild bug)
accept/join nc 127.0.0.1 8081 (A), then again (B) A shows server: client 1 just arrived, B shows nothing about itself
recv flush-per-chunk bug { printf 'par'; sleep 1; printf 'tial\n'; } | send 8081 other clients get exactly one client N: partial — nothing before
multi-line packet printf 'a\nb\n' | send 8081 two lines: client N: a, client N: b
EOF / disconnect printf 'abc' | send 8081 then watch A no text, then server: client N just left (partial dropped)
ids never reused connect, disconnect, connect the new one is client 2, not client 1 again
relay exclusion two nc windows, A types hi + Enter B sees it, A doesn't
leak check valgrind --leak-check=full --track-fds=yes ./mini_serv 8099 + one client session + Ctrl-C no definitely lost, fd count stable
the whole program bash tester/check.sh 13/13 + GRADEME: PASSED

If a row misbehaves, jump to debugging.md §5 (symptom table).


  1. Read §1–§5 (20 min) with experiments 01, 02, 03 running.
  2. Read §6–§8 (15 min) with experiment 04.
  3. Read §9–§10 (10 min), then close this file and go do drills/typing-script.md Stage A + B.

You don't have to become a network engineer. You have to know what each fd, each call and each message means — that's what makes the replay code make sense, and what lets you debug it at the exam instead of panicking.