9.9 KiB
9.9 KiB
mini_serv cheat sheet — the shape to recall on a blank page
Memorize the structure and the exact strings, not a specific file. The exam's
main.cattachment gives youstr_join+extract_messagefor free — you only need the ~85 lines around them.
flowchart LR
M1["1 guard"] --> M2["2 socket"] --> M3["3 bind + listen"] --> M4["4 slots + max_fd"] --> M5["5 select loop"]
M5 --> M6["6 accept gives arrived"] --> M7["7 recv, then buffer, then extract, then relay"] --> M8["8 disconnect gives left + cleanup"]
M8 --> M5
The program in 8 moves
- Guard:
if (argc != 2)→write(2, "Wrong number of arguments\n", 26),return 1. - Server fd:
socket(AF_INET, SOCK_STREAM, 0)→ error?fatal(). - Address:
sockaddr_in,bzero,AF_INET,s_addr = htonl(2130706433)(127.0.0.1),sin_port = htons(atoi(argv[1])). →bind()→listen(). Any failure →fatal(). - Slots: array of clients indexed by fd:
{fd = -1, id = -1, buf = NULL}for allFD_SETSIZE.g_maxfd = server fd. - Loop (every iteration, from scratch):
FD_ZERO;FD_SET(server);FD_SETevery live client fd.select(g_maxfd + 1, &readfds, NULL, NULL, NULL).- server readable →
accept()→ new slot:id = g_next_id++, raiseg_maxfd, broadcast"server: client %d just arrived\n"to others (skip the newcomer). - each live client readable →
recv():<= 0→ disconnect.- else append chunk to that client's buffer (
str_join), then loopextract_message(&buf, &msg) == 1→ build"client %d: " + msg(sprintfinto a malloc'd buffer) → broadcast to others →free(msg)→ repeat.
- Disconnect: save id →
close(fd)→ clear slot →free(buf)→ broadcast"server: client %d just left\n"→ shrinkg_maxfdwhile it points at an empty slot (never below the server fd). Partial line is dropped, not flushed. - Errors:
fatal()=write(2, "Fatal error\n", 12)+exit(1). Neverprintf. No#defineanywhere in the file. - Hygiene:
freethe extracted message;freethe client buffer at disconnect. No leaks. Onlyrecv/sendafterselectsaid the fd is ready.
Canonical body (this is reference/mini_serv.c, annotated)
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/select.h>
typedef struct s_client
{
int fd; /* -1 = slot free */
int id; /* client number, 0,1,2… */
char *buf; /* pending partial line */
} t_client;
static t_client g_c[FD_SETSIZE];
static int g_maxfd; /* highest fd in the sets */
static int g_server; /* listening socket */
static int g_next_id; /* never decreases, never reused */
static void fatal(void)
{
write(2, "Fatal error\n", 12);
exit(1);
}
/* ---- GIVEN in the exam's main.c attachment (copy verbatim) ---- */
static char *str_join(char *buf, char *add); /* append add to buf, free old buf */
static int extract_message(char **buf, char **msg);/* pull one \n line out of *buf */
/* --------------------------------------------------------------- */
static void to_all_except(int fd, char *s) /* broadcast helper */
{
int i = 0;
while (i <= g_maxfd)
{
if (i != fd && g_c[i].fd != -1)
send(g_c[i].fd, s, strlen(s), 0);
i++;
}
}
static void accept_new(void)
{
char msg[64];
int fd;
fd = accept(g_server, NULL, NULL);
if (fd < 0)
return ;
g_c[fd].fd = fd;
g_c[fd].id = g_next_id++;
if (fd > g_maxfd)
g_maxfd = fd;
sprintf(msg, "server: client %d just arrived\n", g_c[fd].id);
to_all_except(fd, msg); /* NOT to the newcomer itself */
}
static void disconnect(int fd)
{
char msg[64];
int 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--;
}
static void handle_read(int fd)
{
char tmp[4096];
char *msg;
char *out;
int n;
n = recv(fd, tmp, sizeof(tmp) - 1, 0);
if (n <= 0)
return (disconnect(fd));
tmp[n] = 0;
g_c[fd].buf = str_join(g_c[fd].buf, tmp); /* append FIRST… */
if (!g_c[fd].buf)
fatal();
while (extract_message(&g_c[fd].buf, &msg) == 1) /* …then pull lines */
{
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);
}
}
int main(int argc, char **argv)
{
struct sockaddr_in addr;
fd_set readfds;
int i;
if (argc != 2)
{
write(2, "Wrong number of arguments\n", 26);
return (1);
}
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 — subject says localhost only */
addr.sin_port = htons(atoi(argv[1]));
if (bind(g_server, (struct sockaddr *)&addr, sizeof(addr)) < 0)
fatal();
if (listen(g_server, 10) < 0)
fatal();
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;
while (1)
{
FD_ZERO(&readfds); /* select destroys the set: rebuild every time */
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 ;
if (FD_ISSET(g_server, &readfds))
accept_new();
i = 0;
while (i <= g_maxfd)
{
if (i != g_server && g_c[i].fd != -1 && FD_ISSET(i, &readfds))
handle_read(i);
i++;
}
}
return (0);
}
The 15 traps (each one has failed someone's exam)
selectwrecks thefd_set— rebuild (or copy from a master set) every loop.nfdsmust beg_maxfd + 1— off-by-one silently ignores your newest fd.- Never
sendto self — checki != fdin the broadcast helper. - Newcomer must NOT receive its own "just arrived" — the expected trace is built that way.
- Don't flush the leftover partial line on disconnect — the trace shows
arrived+leftwith no message for that client. - Append first, extract after — a single
recvcan hold 5 lines, or half a line, or both. recv() <= 0→ disconnect.0is EOF,< 0is error. Both mean: clean up.\x04is data. Only the socket closing is EOF. No special bytes.- Free what
extract_messagehands you (free(msg)) and free the leftover buffer on disconnect. Leak checks exist. printfis not in the allowed list. stderr viawrite(2, …); build strings withsprintf.- No
#definein the submitted file (subject rule). - Only bind
127.0.0.1—htonl(2130706433). NotINADDR_ANY. - Sending back to a client that just died can
SIGPIPE-kill you — the official test never does this (clients are serialized), so don't over-engineer; if you finish early and want armor,signal(SIGPIPE, SIG_IGN)is the classic line (check your subject's allowed functions first). acceptfailing is not fatal — justreturn.g_maxfdcan shrink — keep it ≥ server fd orselectstops seeing the listener.
The real test, decoded
tester/grademe/ is the actual exam-style runner: a listener (client 0) connects, then clients 1…9 connect / send / leave, and the listener's exact bytes are diffed. Reading normal.output tells you the ground truth:
server: client 1 just arrived
client 1: Si vous ne voyez QUE ce message, c'est mauvais signe. ← line relayed
server: client 1 just left ← sender closed
server: client 2 just arrived
client 2: Bienvenue sur le test de votre miniserv
server: client 2 just left
server: client 3 just arrived
client 3: Ceci est un message
server: client 3 just left
server: client 4 just arrived
server: client 4 just left ← sent text with NO \n → nothing relayed, buffer dropped
server: client 5 just arrived
server: client 5 just left ← same, and note: no leftover ever appears
server: client 6 just arrived
client 6: Et voici un texte avec plusieurs ← one packet, 5 lines → 5 prefixed lines
client 6: retours
client 6: a
client 6: la
client 6: ligne
server: client 6 just left
server: client 7 just arrived
server: client 7 just left ← word-bursts incl. a literal ^D byte, no \n → silence
server: client 8 just arrived
server: client 8 just left ← 10 320-byte line with no \n → silence
server: client 9 just arrived
client 9: desu…desu ← 364 KB as ONE line, relayed whole
server: client 9 just left
Also tested (seen in the runner): no-arg error, Fatal error on bind failure, exit status 1.
Duration of the real runner is ~20–30 s (it sleeps between clients). Don't "optimize" buffers
for it — send as soon as a line is complete.
Exam-shell reality check
- You will write one file:
mini_serv.c, in therendudirectory the shell shows you. - Compile:
cc -Wall -Wextra -Werror mini_serv.c -o mini_serv(the runner compiles for you too). - Test with a second terminal
nc 127.0.0.1 <port>before submitting — 3 minutes ofnccatches 90% of bugs. - Submit with the shell's submit command (
grademe) — do it early, then again after fixes.