9.0 KiB
Diagrams — mini_serv from scratch, one picture at a time
Read in order. Each diagram is a layer: processes → fd table → address → door → state → the loop → accept → data → disconnect → ids → memory → errors → one full session. Final code:
exam-answer/mini_serv.c.
1. The whole system
Three processes, three fd tables, two TCP connections. A socket fd is only meaningful inside the process that owns it — the same TCP connection appears as a different fd in each process.
flowchart LR
A["client A process<br/>own fd table<br/>fd 3 = its socket"] -- "TCP connection" --> K["kernel<br/>socket objects +<br/>send/recv buffers"]
B["client B process<br/>own fd table<br/>fd 3 = its socket"] -- "TCP connection" --> K
K -- "same connections,<br/>seen from the server side" --> S["mini_serv process<br/>fd 3 = listening socket<br/>fd 4 = A's socket<br/>fd 5 = B's socket"]
2. One process's fd table
The kernel assigns the lowest free number. 0/1/2 are always taken by stdio, so the first socket is usually 3. The listening socket and each client socket are separate entries.
flowchart LR
T["fd table of mini_serv"] --> F0["0 — stdin"]
T --> F1["1 — stdout"]
T --> F2["2 — stderr"]
T --> F3["3 — listening socket<br/>127.0.0.1:8081"]
T --> F4["4 — client A socket"]
T --> F5["5 — client B socket"]
T --> FN["... up to 1023<br/>(FD_SETSIZE)"]
3. The address you bind
bind reads the whole struct, so it must be zeroed first. The IP is the number
2130706433 = 0x7F000001 = 127.0.0.1, in network byte order.
flowchart TD
A["struct sockaddr_in addr"] --> B["sin_family = AF_INET"]
A --> C["sin_port = htons(atoi(argv[1]))"]
A --> D["sin_addr.s_addr = htonl(2130706433)"]
D --> E["2130706433 = 0x7F000001<br/>= 127.0.0.1"]
C --> F["network byte order"]
E --> G["bind() claims 127.0.0.1:port"]
F --> G
4. The door: socket → bind → listen → accept
listen does not accept anything; it asks the kernel to queue completed handshakes. Each
accept pops one and returns a new fd. The listening fd keeps listening forever.
flowchart LR
S["socket()<br/>one new fd"] --> B["bind()<br/>claim 127.0.0.1:port"]
B --> L["listen(10)<br/>mark as accepting"]
L --> Q["kernel accept queue<br/>up to 10 completed handshakes"]
Q -- "accept() pops ONE" --> C["new fd for that conversation"]
L -.->|keeps listening forever| L
5. The state arrays, indexed by fd
There is no client struct. The fd is the slot number, and two arrays hold everything the server must remember about that slot.
flowchart TD
FD4["fd 4"] --> ID4["g_id[4] = 0"]
FD4 --> B4["g_buf[4] = NULL"]
FD5["fd 5"] --> ID5["g_id[5] = 1"]
FD5 --> B5["g_buf[5] = a partial line, e.g. 'wor'"]
ID4 --> FREE["g_id[fd] = -1 means: slot is free"]
B5 --> FREE2["g_buf[fd] is freed when the client leaves"]
6. One client slot's life
The same slot moves through four states. Note that recv 0 or -1 can arrive in either
connected state, and a partial line is dropped in both.
stateDiagram-v2
[*] --> Free
Free --> Connected: accept / id = g_nextid++, g_buf = NULL
Connected --> Buffering: recv data without a newline
Buffering --> Connected: newline found / relay the line, keep remainder
Connected --> Free: recv returns 0 or -1 / announce left, close, free
Buffering --> Free: recv returns 0 or -1 / drop buffer, announce left, close
7. The heartbeat: rebuild → select → dispatch
Every iteration starts from an empty bitmap because select destroys the one you give it.
select returns when at least one watched fd is ready.
flowchart TD
A["iteration start"] --> B["FD_ZERO: empty bitmap"]
B --> C["FD_SET(g_server)"]
C --> D["for fd 0..g_maxfd:<br/>if the slot is live, FD_SET(fd)"]
D --> E["select(g_maxfd + 1, &readfds, NULL, NULL, NULL)"]
E --> F{"select < 0 ?"}
F -- yes --> A
F -- no --> G["readfds now contains ONLY ready fds"]
G --> H{"FD_ISSET(g_server) ?"}
H -- yes --> I["on_accept()"]
H -- no --> J{"FD_ISSET(a client) ?"}
I --> A
J -- yes --> K["on_read(fd)"]
J -- no --> A
K --> A
8. Why the bitmap must be rebuilt: select rewrites it
Before the call, the bitmap means "watch these". After the call, it means "these were ready".
The next iteration needs the first meaning again, so it is rebuilt from g_id[].
flowchart LR
A["before select<br/>bits 3, 4, 5 set"] --> B["select()"]
B --> C["after select<br/>only READY bits remain<br/>e.g. bit 4"]
C --> D["those bits are your to-do list"]
D --> E["handle fd 4"]
E --> F["next iteration:<br/>rebuild from g_id[]"]
F --> A
9. Accept: a new client, step by step
flowchart TD
A["g_server readable"] --> B["fd = accept(g_server, NULL, NULL)"]
B --> C{"fd < 0 ?"}
C -- yes --> D["return — keep serving"]
C -- no --> E{"fd >= FD_SETSIZE ?"}
E -- yes --> F["close(fd) — select cannot watch it"]
E -- no --> G["g_id[fd] = g_nextid++"]
G --> H["g_buf[fd] = NULL"]
H --> I["g_maxfd = max(g_maxfd, fd)"]
I --> J["sprintf: server: client N just arrived"]
J --> K["send_all(fd, msg)<br/>everyone EXCEPT the newcomer"]
10. The data pipeline: bytes in → lines out
This is the part the exam is really testing. Append first (a chunk can end mid-line), then cut complete lines in a loop, build one prefixed string per line, send to the others.
flowchart TD
A["recv chunk 1: 'hel'"] --> B["g_buf[fd] = 'hel'"]
B --> C{"contains a newline ?"}
C -- no --> D["send nothing — wait"]
D --> E["recv chunk 2: 'lo' newline 'world' newline"]
E --> F["append → 'hello' newline 'world' newline"]
F --> G["extract_message loop"]
G --> H["line: 'hello' newline"]
H --> I["out = 'client 1: hello' newline"]
I --> J["send_all(sender, out) — others only"]
G --> K["line: 'world' newline"]
K --> L["out = 'client 1: world' newline"]
L --> J
G --> M["remainder (empty here) stays in g_buf"]
11. Disconnect: order matters
flowchart TD
A["recv returns 0 (EOF)<br/>or -1 (error)"] --> B["on_leave(fd)"]
B --> C["id = g_id[fd] — save it FIRST"]
C --> D["close(fd)"]
D --> E["g_id[fd] = -1"]
E --> F["free(g_buf[fd])<br/>DROP the partial line, never flush it"]
F --> G["sprintf: server: client N just left"]
G --> H["send_all(-1, msg) — everyone left"]
H --> I["shrink g_maxfd while the last slot is empty<br/>and g_maxfd > g_server"]
12. fds are recycled; ids are not
flowchart TD
L["listener: id 0"] --> A["Alice: fd 4, id 1"]
A --> X["Alice leaves"]
X --> R["kernel may reuse fd 4"]
X --> N["g_nextid stays 2"]
R --> B["Bob gets fd 4 again"]
N --> B2["Bob gets id 2"]
B --> Z["fd: recycled by the kernel"]
B2 --> Y["id: never reused by you"]
13. Memory ownership: who frees what
flowchart LR
A["str_join"] -->|"returns a new buffer,<br/>frees the old one"| B["g_buf[fd]"]
C["extract_message"] -->|"returns one line,<br/>a slice of the old buffer"| D["line — free after send"]
C -->|"returns the remainder"| B
E["malloc(strlen(line) + 64)"] --> F["out — free after send"]
G["accept()"] --> H["fd — close in on_leave"]
I["free(g_buf[fd])"] --> B
14. Every error path in the program
The rule from the subject: failures before accepting are fatal (Fatal error + exit 1);
failures after accepting must keep the server alive.
flowchart TD
A["program start"] --> B{"argc == 2 ?"}
B -- no --> B1["stderr: Wrong number of arguments<br/>exit 1"]
B -- yes --> C{"socket / bind / listen ok ?"}
C -- no --> C1["stderr: Fatal error<br/>exit 1"]
C -- yes --> D["enter the select loop"]
D --> E{"accept fails ?"}
E -- yes --> E1["return — keep serving"]
D --> F{"recv returns 0 or -1 ?"}
F -- yes --> F1["disconnect — keep serving"]
15. One full session, in order
sequenceDiagram
participant L as Listener id 0
participant S as mini_serv
participant A as Alice id 1
participant B as Bob id 2
A->>S: connect
S-->>L: server: client 1 just arrived
A->>S: hello + newline
S-->>L: client 1: hello
A->>S: par (no newline)
Note over S: g_buf[Alice] = "par" — nothing sent
A->>S: tial + newline
S-->>L: client 1: partial
A->>S: close (EOF)
S-->>L: server: client 1 just left
B->>S: connect (reuses Alice's fd 4)
S-->>L: server: client 2 just arrived
The whole thing on one line
fd table → bind/listen door → rebuild bitmap → select → accept or recv → append → cut
lines → send to others → on EOF close/free/announce. Every diagram above is one arrow of
that sentence, and every condition in the code is a fork in one of them.