Files
42-exam06/walkthrough.md
T

17 KiB
Raw Blame History

Walkthrough — every block of code, then the behavior it produces

How to use this file. Keep reference/mini_serv.c open next to it. Go station by station: read the code, predict what the behaviour probe will show, then run it. Every block marked See it contains real output captured from this machine — if yours differs, you just found your bug.

Helper used in the probes (same trick the grader uses):

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

Station map:

flowchart LR
    S1["1-4 · stages A-B<br/>file top, fatal, socket, bind+listen"] --> S2["5-6 · stage C<br/>slots + select loop"]
    S2 --> S3["7-8 · stage C<br/>accept + broadcast"]
    S3 --> S4["9-10 · stage D<br/>recv, buffer, extract, relay"]
    S4 --> S5["11 · stage E<br/>disconnect + cleanup"]
    S5 --> S6["12 · stage F<br/>the graders"]
    S6 --> S7["13-14 · audit + self-quiz"]

Stations carry their typing-script.md stage tag so you can work in parallel with drilling.


Station 1 · Top of the file: includes, struct, globals [stage A]

typedef struct s_client { int fd; int id; char *buf; } t_client;
static t_client g_c[FD_SETSIZE];
static int g_maxfd, g_server, g_next_id;
  • fd — slot marker: -1 means "not a client". That's why the array can be indexed by fd.
  • id — the number announced in messages; not the fd (fds get recycled, ids never do).
  • buf — the pending partial line (append with str_join, mine lines with extract_message).
  • g_c[FD_SETSIZE] — one slot per possible fd; FD_SETSIZE is 1024, the ceiling of select.
  • g_maxfd — highest fd in use; select and every scan loop depend on it.
  • g_server — the listening fd, kept separately so max_fd shrinking never drops it.
  • g_next_id — the counter behind id; only ever increments.

See it — nothing runs, but it must compile clean:

$ cc -Wall -Wextra -Werror -c reference/mini_serv.c -o /tmp/x.o
$ echo $?
0

If this fails, you're not writing mini_serv yet, you're writing C. Fix that first.


Station 2 · fatal() and the argument guard [stage B]

static void fatal(void) { write(2, "Fatal error\n", 12); exit(1); }

if (argc != 2)
{
    write(2, "Wrong number of arguments\n", 26);
    return (1);
}
  • write(2, ...) — fd 2 is stderr (never stdout, never printf).
  • The \n is inside the string, and the length counts it: "Fatal error\n" = 12, "Wrong number of arguments\n" = 26. The grader diffs these bytes.
  • Both paths exit status 1.

See it:

$ ./mini_serv
Wrong number of arguments
$ echo $?
1

$ ./mini_serv 1        # port 1 needs root → bind fails → fatal()
Fatal error
$ echo $?
1

The port-1 trick is a free way to test the Fatal error path on purpose. Grader link: behavioral tests 1 (bad args) and 2 (bind failure).


Station 3 · socket() and the address struct [stage B]

g_server = socket(AF_INET, SOCK_STREAM, 0);
if (g_server < 0) fatal();
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(2130706433);   /* 127.0.0.1 */
addr.sin_port = htons(atoi(argv[1]));
  • AF_INET + SOCK_STREAM = IPv4 + TCP.
  • bzero — zero the struct first, or bind reads garbage.
  • 2130706433 = 0x7F000001 = the four bytes 127.0.0.1. htonl converts to network byte order.
  • atoi(argv[1]) — argv is text; htons again for byte order.

See it — the kernel gives your new socket the lowest free fd, and /proc shows it:

$ ls -l /proc/$PID/fd
0 -> /dev/null
1 -> /dev/null
2 -> /dev/null
3 -> socket:[870369]      <- the listening socket

Station 4 · bind + listen — becoming reachable [stage B]

if (bind(g_server, (struct sockaddr *)&addr, sizeof(addr)) < 0) fatal();
if (listen(g_server, 10) < 0) fatal();
  • bind claims 127.0.0.1:port; captured errors go to fatal().
  • The cast to struct sockaddr * is just C's way of passing a concrete struct to a generic API.
  • listen(fd, 10) turns on accepting; 10 is the kernel backlog (queue of connected-but-unaccepted clients).

See it:

$ ss -tlnp | grep 8091
LISTEN 0 10 127.0.0.1:8091 0.0.0.0:* users:(("ref_mini_serv",pid=127850,fd=3))

Read that line: state LISTEN, backlog 10, address 127.0.0.1:8091, and the program's listening fd=3. A second instance on the same port gets Fatal error (bind → EADDRINUSE). The full "connections queue before accept" demo is explore/02_bind_listen.c.


Station 5 · Slot initialisation and g_maxfd [stage C]

i = 0;
while (i < FD_SETSIZE) { g_c[i].fd = -1; g_c[i].id = -1; g_c[i].buf = NULL; i++; }
g_maxfd = g_server;

Behavior: the invariant everything else assumes: "every loop scans 0..g_maxfd, and any slot with fd != -1 is a live client".

How it breaks (and where you'll see it): forget to raise g_maxfd in accept_new and the second client is invisible — you'll see it immediately in the 25-client behavioral test ("only the first one works").


Station 6 · Loop head: rebuild the set, then sleep [stage C]

while (1)
{
    FD_ZERO(&readfds);
    FD_SET(g_server, &readfds);
    i = 0;
    while (i <= g_maxfd) { if (g_c[i].fd != -1) FD_SET(i, &readfds); i++; }
    if (select(g_maxfd + 1, &readfds, NULL, NULL, NULL) < 0) continue ;
  • FD_ZERO — fresh bitmap every iteration, because select destroys the one you give it.
  • FD_SET(g_server) — the listener is the source of "new connection" events.
  • FD_SET(i) for each live client — the sources of data/EOF events.
  • select(max + 1, ...) — nfds = "watch fds 0..max". Sleep until any watched fd is ready.
  • < 0 (e.g. EINTR) — just retry; do not exit the server for a signal poke.

See it — an idle server must be asleep, not spinning:

$ ps -o %cpu= -p $PID
 0.0

If you see ~100% with no clients, you broke the rebuild (or never consumed readiness) — that is the single most common exam bug. See debugging.md §5.


Station 7 · accept_new() — a client is born [stage C]

fd = accept(g_server, NULL, NULL);
if (fd < 0) return ;
g_c[fd].fd = fd;
g_c[fd].id = g_next_id++;
g_c[fd].buf = NULL;
if (fd > g_maxfd) g_maxfd = fd;
sprintf(msg, "server: client %d just arrived\n", g_c[fd].id);
to_all_except(fd, msg);
  • accept returns a new fd per connection (the listener keeps listening).
  • id = g_next_id++ — 0, 1, 2, … forever. Independent of fd.
  • buf = NULL — fresh client, empty pending line.
  • g_maxfd rises so the next select watches the newcomer.
  • to_all_except(fd, ...) — not to the newcomer.

See it — two terminals connect; only the older one hears about it:

# terminal A: nc 127.0.0.1 8091     (connects, sees nothing yet)
# terminal B: nc 127.0.0.1 8091     (connects)
# terminal A now shows:
server: client 1 just arrived
# terminal B shows nothing — and that is CORRECT (arrival is "others only")

And the fd table grows while they're connected:

$ ls -l /proc/$PID/fd
3 -> socket:[870369]      <- listener
4 -> socket:[872305]      <- client A
5 -> socket:[872306]      <- client B

$ ss -tn | grep 8095
ESTAB 30 0 127.0.0.1:57962 127.0.0.1:8095
ESTAB 0  0 127.0.0.1:57974 127.0.0.1:8095

ids vs fds: right now A has fd 4 / id 0, B has fd 5 / id 1. Disconnect A, connect C — C gets fd 4 again (kernel recycles) but id 2 (your counter never recycles). The grader checks the id.


Station 8 · to_all_except() — the loudspeaker [stage C/D]

i = 0;
while (i <= g_maxfd)
{
    if (i != fd && g_c[i].fd != -1)
        send(g_c[i].fd, s, strlen(s), 0);
    i++;
}
  • Skip the source (i != fd), skip dead slots (fd != -1), send the whole message in one call.
  • fd = -1 means "everyone" (used for departures).

See it: in terminal A press keys + Enter → terminal B shows client 0: hihi. Terminal A shows nothing of itself. If the sender does see its own message, you removed this check — that's behavioral test 4 failing.


Station 9 · handle_read() part 1 — recv and append [stage D]

n = recv(fd, tmp, sizeof(tmp) - 1, 0);
if (n <= 0) { disconnect(fd); return ; }
tmp[n] = 0;
g_c[fd].buf = str_join(g_c[fd].buf, tmp);
if (!g_c[fd].buf) fatal();
  • sizeof(tmp) - 1 — room for your own \0 at tmp[n].
  • n <= 0 — 0 is EOF, < 0 is error; both mean "client is gone".
  • Append before extracting: a packet may hold 5 lines, half a line, or both.
  • str_join returns a new heap string and frees the old one; NULL means OOM → fatal.

See it — this is a real captured session. Add three temporary prints (recipe below), connect one listener + one sender, send hel then lo+world:

[recv] fd=5 n=3
[buf ] fd=5 buf="hel"
[recv] fd=5 n=9
[buf ] fd=5 buf="hello
world
"

Read it carefully: 3 bytes arrive, the buffer holds hel — nothing is sent (no \n). Then 9 more bytes arrive; the buffer now holds hello\nworld\n. The temp prints:

fprintf(stderr, "[recv] fd=%d n=%d\n", fd, n);                 /* after tmp[n] = 0 */
fprintf(stderr, "[buf ] fd=%d buf=\"%s\"\n", fd, g_c[fd].buf);  /* before the while */

Behavior drills (with the send() helper, other client watching):

input other side sees why
printf 'hello\n' | send 8091 client 1: hello complete line
{ printf 'par'; sleep 1; printf 'tial\n'; } | send 8091 one client 1: partial only after the second chunk buffer holds, no early flush
printf 'a\nb\n' | send 8091 client 1: a then client 1: b per-line relay
printf 'abc' | send 8091 (then close) nothing + just left leftover dropped

Station 10 · handle_read() part 2 — extract, build, send, free [stage D]

while (extract_message(&g_c[fd].buf, &msg) == 1)
{
    out = malloc(strlen(msg) + 64);
    if (!out) { free(msg); fatal(); }
    sprintf(out, "client %d: %s", g_c[fd].id, msg);
    to_all_except(fd, out);
    free(out);
    free(msg);
}
  • while (... == 1) — one iteration per complete line in the buffer.
  • malloc(strlen(msg) + 64) — room for "client N: " + line + \0; a line can be 364 KB, so you must size it, never use a fixed buffer.
  • sprintf builds the exact wire format; send delivers it to others only.
  • free(out) and free(msg) — extract_message handed you ownership of that slice.

See it (same captured session, right after Station 9's output):

[send] fd=5 to_others="client 1: hello
"
[send] fd=5 to_others="client 1: world
"

Two sends from one recv of 9 bytes — the buffer produced two complete lines. Grader link: tests 4–6 (relay, split, multiline) and the 400 KB test.


Station 11 · disconnect() — goodbye, cleanly [stage E]

id = g_c[fd].id;
close(fd);
g_c[fd].fd = -1;
g_c[fd].id = -1;
free(g_c[fd].buf);
g_c[fd].buf = NULL;
sprintf(msg, "server: client %d just left\n", id);
to_all_except(-1, msg);
while (g_maxfd > g_server && g_c[g_maxfd].fd == -1) g_maxfd--;
  • Save id first — after clearing the slot you can't build the message.
  • close + mark dead + free the pending line (which is dropped, never flushed).
  • Broadcast to everyone; then let g_maxfd fall back over empty trailing slots (but never below g_server, or select stops watching the listener).

See it:

# terminal A watching; in B press Ctrl-C (or let the scripted sender end)
# terminal A shows:
server: client 1 just left

$ ls -l /proc/$PID/fd        # after everyone left
3 -> socket:[870369]         # back to the listener only — no fd leak

Partial-drop proof: printf 'abc' | send 8091 then A shows only just left — no abc. Grader link: test 6 (no-flush) and test 13 (fd stability).


Station 12 · The whole program, graded [stage F]

$ bash tester/check.sh
== [1/3] strict compile: cc -Wall -Wextra -Werror ==
OK -> .../sandbox/mini_serv
== [2/3] behavioral tester ==
... 13 × PASS ...
all tests passed.
== [3/3] grademe final boss (exact exam-style diff, ~25s) ==
GRADEME: PASSED

On failure, sandbox/traceback shows expected-vs-yours, first difference first. Map of ground truth → implementation:

Grader expectation Implemented in
exact arg/bind errors + exit 1 Station 2
arrival to others only Station 7 + 8
per-line prefix relay Station 10
split lines reassembled Station 9
partial dropped on disconnect Station 11
ids monotonic Station 7
364 KB line Station 10 (malloc(strlen+64))
fd/memory cleanliness Stations 11 + 13

Station 13 · Audit day: valgrind tells the truth (and one honest finding)

$ valgrind --leak-check=full --track-fds=yes ./mini_serv 8093
# ... run a small session: two clients chat, one leaves mid-line, then Ctrl-C the server ...
==129228== HEAP SUMMARY:
==129228==     in use at exit: 0 bytes in 0 blocks
==129228== All heap blocks were freed -- no leaks are possible

That's the line you want. Now the honest finding from the same session — this happened:

==129228== Process terminating with default action of signal 13 (SIGPIPE)
==129228==    at ... send
==129228==    by ... to_all_except
==129228==    by ... disconnect
==129228==    by ... handle_read

The server was killed by SIGPIPE because my test client closed a socket while it had unread messages waiting (that makes the kernel answer with RST; the next send to it raises EPIPE + SIGPIPE, default action: die). The official grader never does that — its clients read everything or close cleanly one at a time — which is why plain send passes. Options if you want armor anyway: send(fd, s, len, MSG_NOSIGNAL) (Linux; send is allowed), or signal(SIGPIPE, SIG_IGN) (not in the allowed list — only with care). Exit code when it happens to you: 141 (128+13).

Same report, the other line:

==129228== FILE DESCRIPTORS: 5 open (3 inherited) at exit.

"3 inherited" = stdin/out/err; the others are sockets that existed when the signal killed the process mid-loop — not a leak. The leak check that matters is behavioral: connect and disconnect clients, watch /proc/$PID/fd return to listener-only (Station 11) — that's exactly what behavioral test 13 automates.


Station 14 · Self-quiz (answers at the bottom)

  1. Which fd is the listener in this program, and what changes it?
  2. B connects; why does B receive nothing about itself — and what would break if it did?
  3. A sends x\ny (no trailing newline). What do others see right now? What stays in A's buffer?
  4. Why is A's leftover buffer dropped rather than sent at disconnect?
  5. Two clients come and go. Who decides the ids, and what happens to ids vs fds on reuse?
  6. select(4, ...) — which fds are being watched? What breaks if the real max fd is 7?
  7. After recv returns, which two conditions must handle_read distinguish?
  8. Why is free(msg) required after the relay send, and who frees out?
  9. Idle server at 100% CPU — name two causes.
  10. Server dies with no message, exit code 141 — cause, and the exam-relevant stance?
Answers
  1. fd 3 — the first fd after stdio; if you open files before socket(), it shifts. Always track it in g_server; never hardcode it.
  2. Arrival is broadcast to others only (subject + trace). If B heard its own arrival, the grader's expected output (listener's byte stream) would gain an extra line → diff fails.
  3. Others see nothing yet — no \n was received. The buffer holds "x\ny". When the next chunk arrives, the first complete line (x) is relayed and the remainder stays.
  4. The subject says leftovers are not messages; the expected trace shows arrived+left with nothing between. Flushing it would inject a phantom client N: ... line.
  5. g_next_id++ at accept — monotonic forever. fds are recycled by the kernel; ids are never reused.
  6. fds 0..3. With real max 7, fds 4–7 are watched by nobody → clients 4–7 pile up data silently; always select(g_maxfd + 1, ...) and raise g_maxfd on accept.
  7. n > 0 → append + extract + relay; n <= 0 (EOF or error) → disconnect. Same branch for both, different meaning from n > 0.
  8. extract_message hands you a slice of the old buffer (*msg = *buf); it's yours to free after use. out is malloc'd right there — freed right after send.
  9. (a) the fd_set isn't rebuilt/copied before select; (b) a ready fd isn't consumed (e.g. accept never called), so select returns immediately forever.
  10. SIGPIPE from send after the peer reset (rude close with unread data). Official test never triggers it; keep plain send and know the signature, or add MSG_NOSIGNAL.