Files
42-exam06/libc-reference.md

18 KiB

libc & syscall reference — every call mini_serv uses, one by one

A lookup table, not a reading book. When a call returns -1, or you can't remember what accept returns, or what nfds means — find the entry here.

Context: man pages exist on 42 machines. man 2 <syscall> (kernel, e.g. man 2 recv) vs man 3 <function> (libc, e.g. man 3 printf). man 7 socket, man 7 tcp are gold. Read the RETURN VALUE section first in any man page — it's where the bugs live.

The whole program in one picture (every call in this file appears here):

flowchart TD
    A["socket()"] -->|"-1"| F1["write(2, 'Fatal error\n') + exit(1)"]
    A -->|"fd >= 0"| B["bind()"]
    B -->|"!= 0"| F1
    B --> C["listen()"]
    C -->|"!= 0"| F1
    C --> L["LOOP: select() — sleep until any fd is ready"]
    L -->|"listen fd ready"| AC["accept() gives a NEW fd<br/>broadcast 'just arrived' to the others"]
    L -->|"client fd ready"| RC["recv()"]
    RC -->|"0 = EOF, or -1"| LV["broadcast 'just left'<br/>FD_CLR + close + free"]
    RC -->|"n > 0"| BUF["append to that client's buffer<br/>extract complete lines"]
    BUF --> SD["send() 'client N: line'<br/>to the other clients"]
    AC --> L
    LV --> L
    SD --> L

0. The four families (they behave differently)

Family Examples Failure style
Syscalls (kernel) socket bind listen accept recv send select write close return -1 and set errno
Macros / inline FD_ZERO FD_SET FD_CLR FD_ISSET htons htonl can't fail, pure bit math
libc helpers malloc calloc realloc free strlen strcpy strcat memset bzero sprintf atoi return NULL / garbage / nothing
Types & constants fd_set sockaddr sockaddr_in socklen_t AF_INET SOCK_STREAM FD_SETSIZE not callable, just vocabulary

1. Networking syscalls

socket — create a network endpoint

int socket(int domain, int type, int protocol);
  • domain: AF_INET = IPv4 (the exam allows nothing else)
  • type: SOCK_STREAM = TCP (reliable, ordered byte stream)
  • protocol: 0 (default for that pair)
  • Returns: a new fd >= 0, or -1 + errno (e.g. EMFILE = too many fds)
  • Exam pattern: g_server = socket(AF_INET, SOCK_STREAM, 0); if (g_server < 0) fatal();
  • Remember: this fd is the listener — it never carries chat data.

bind — attach an address+port to a socket

int bind(int fd, const struct sockaddr *addr, socklen_t len);
  • fd: the socket from above
  • addr: your filled sockaddr_in, cast to struct sockaddr * (that's what the API wants)
  • len: sizeof(struct sockaddr_in) (or sizeof(addr) for the variable)
  • Returns: 0 ok, -1 + errno
  • Errors you'll actually see: EADDRINUSE (port busy — the grader may pick another port), EACCES (privileged port, don't use <1024), EINVAL (already bound)
  • Exam pattern: fill + if (bind(...) < 0) fatal();
  • Trap: forgetting memset/bzero on the struct → garbage address fields.

listen — mark the socket as accepting connections

int listen(int fd, int backlog);
  • backlog: how many not-yet-accepted connections the kernel may queue (exam code uses 10)
  • Returns: 0 / -1
  • Exam pattern: if (listen(g_server, 10) < 0) fatal();
  • Remember: after listen, clients can already connect (the kernel completes the TCP handshake); accept just dequeues them. See explore/02_bind_listen.c.

accept — dequeue one pending connection

int accept(int listen_fd, struct sockaddr *addr, socklen_t *len);
  • listen_fd: the listening fd (not a client)
  • addr / len: where to write the peer's address — the exam passes NULL, NULL
  • Returns: a NEW fd for that one conversation, or -1 + errno
  • Exam pattern:
    fd = accept(g_server, NULL, NULL);
    if (fd < 0) return ;          /* not fatal! */
    
  • Traps:
    • it returns a different fd than the one you passed — the client count grows by 1 fd;
    • a fresh fd is created for every connection, even from the same machine;
    • far more than backlog clients connecting without accept → connections queue/time out.

recv — read bytes from a connected socket

ssize_t recv(int fd, void *buf, size_t len, int flags);
  • fd: a connected client fd (never the listener)
  • buf, len: your buffer and its capacity (sizeof buf - 1 if you null-terminate yourself)
  • flags: 0 here
  • Returns: > 0 bytes received; 0 = EOF (peer closed/shutdown its writing side); -1 = error + errno (ECONNRESET, EBADF, EAGAIN if non-blocking…)
  • Exam pattern: call only when select said the fd is readable; then if (n <= 0) disconnect(fd); else { buf[n] = 0; append to client's buffer; extract lines; }
  • Traps:
    • no message boundaries — a "line" can arrive in pieces or several lines at once;
    • 0 is not an error, it's a goodbye;
    • -1 with EINTR can be retried; the official test never provokes it.

send — write bytes to a connected socket

ssize_t send(int fd, const void *buf, size_t len, int flags);
  • Returns: bytes queued to the kernel (may be less than len), or -1
  • Errors: EPIPE (= peer gone; also raises SIGPIPE, see §6), ECONNRESET, EAGAIN
  • Exam pattern: send(fd, s, strlen(s), 0); — one call per complete message, no retry loops. All passing solutions do exactly this (the official test drains, so partial sends don't bite).
  • Trap: strlen(s) is what you send — forget it and you send garbage if s isn't terminated.

close — release an fd

int close(int fd);
  • Returns: 0 / -1
  • Exam pattern: on disconnect: FD_CLR the client (from your master set), close(fd), free its buffer.
  • Traps: closing an fd that's still in an fd_set → next select fails with EBADF; double close = UB (may close a new innocent fd!).

fcntl — the subject hints at it (you don't need it)

fcntl(fd, F_SETFL, O_NONBLOCK);

The subject says: "you should use fcntl(fd, F_SETFL, O_NONBLOCK) but use select and NEVER check EAGAIN". Translation: in this exam, do not make sockets non-blocking manually and never loop on EAGAIN. Just don't call recv/send before select said the fd is ready. Passing solutions don't call fcntl at all.


2. Waiting: select and the FD_* macros

The whole family is one idea: a bitmap

fd_set is not a list of fds — it is a fixed-size bitmap with one bit per fd number. Bit n = "fd n is in this set". There are FD_SETSIZE bits (1024 on Linux), so fd numbers 0..1023 are all you can watch.

FD_ZERO(&set)    0000 0000 0000 0000      nobody watched
FD_SET(3, &set)  0000 0000 0000 1000      bit 3 on
FD_SET(5, &set)  0000 0000 0010 1000      bits 5 and 3
FD_CLR(3, &set)  0000 0000 0010 0000      bit 3 off
FD_ISSET(5, s)   non-zero (true)          is bit 5 on?
Member Kind Meaning Exam use
fd_set type the bitmap itself one readfds per loop + a master or rebuild
FD_SETSIZE constant number of bits = 1024 = highest fd you can watch + 1 array sizes; reject fds >= it
FD_ZERO(&s) macro clear all bits first line of every loop iteration
FD_SET(fd, &s) macro turn bit fd on add the listener + every live client
FD_CLR(fd, &s) macro turn bit fd off when a client leaves (before/at close)
FD_ISSET(fd, &s) macro test bit fd after select: was this fd ready?
select(nfds, &r, &w, &e, timeout) syscall sleep until a watched fd is ready, then keep only the ready bits the heartbeat

Two contracts that cause almost every bug:

  1. nfds = highest fd in the set + 1. The kernel only looks at bits 0..nfds-1; a client with a higher fd is invisible. FD_SETSIZE is not the right value — max + 1 is.
  2. select rewrites the set in place (it is an in/out parameter). On return, only the ready fds still have their bits. Hence: rebuild from your slot array every iteration (reference/mini_serv.c), or keep a master and copy it before each call (your friend's variant with active_fds).

What "ready" means: listening fd readable = a connection is waiting; client fd readable = bytes arrived or EOF is pending (so FD_ISSET does not distinguish data from goodbye — recv does).

Pitfalls: no FD_ZERO (garbage bits → EBADF/spurious readiness); checking FD_ISSET against the master instead of the copy; clearing a bit after close instead of before; FD_SET only marks a bit — it does not open an fd, and selecting a bit for a closed fd fails with EBADF; fd >= FD_SETSIZE (undefined/overflow); using poll-style thinking (select's return is a count, not a list).

select — sleep until any watched fd is ready

int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
  • nfds: highest fd in your sets + 1. Wrong value = newest clients invisible.
  • readfds: fds you want to know "has data / new connection / EOF"
  • writefds: fds that can accept writes "now" (a healthy TCP socket almost always can)
  • exceptfds: out-of-band data — NULL for this exam
  • timeout: NULL = block forever (what mini_serv wants)
  • Returns: number of ready fds; 0 = timeout (won't happen with NULL); -1 + errno (EBADF = fd in set closed/not valid; EINVAL = nfds bogus; EINTR = signal, retry)
  • THE trap: select overwrites the sets with only the ready ones. Start every iteration from a fresh/master set.
  • Exam pattern:
    FD_ZERO(&readfds);
    FD_SET(g_server, &readfds);
    for (i = 0; i <= g_maxfd; i++)
        if (g_c[i].fd != -1)
            FD_SET(i, &readfds);
    if (select(g_maxfd + 1, &readfds, NULL, NULL, NULL) < 0)
        continue ;
    
flowchart LR
    M["your source of truth: master set / slots array<br/>server fd + every live client"] -->|"rebuild or copy BEFORE every select"| SE["read_fds that you pass to select()"]
    SE -->|"select returns: only the READY bits remain"| CH["FD_ISSET checks decide who to serve"]
    CH --> M

FD_ZERO / FD_SET / FD_CLR / FD_ISSET

void FD_ZERO(fd_set *set);
void FD_SET(int fd, fd_set *set);
void FD_CLR(int fd, fd_set *set);
int  FD_ISSET(int fd, fd_set *set);
  • A fd_set is a bitmap of fd numbers. FD_ISSET after select = "this fd is ready".
  • FD_CLR when a client leaves (before/at close) — otherwise select sees a dead fd.
  • FD_SETSIZE is 1024: only fds 0..1023 can be watched at all. That's why client tables are [1024]. Fd numbers can't exceed it on Linux for this purpose.

3. I/O and formatting

write — raw output, no formatting

ssize_t write(int fd, const void *buf, size_t count);
  • Exam pattern (errors): write(2, "Fatal error\n", 12); — fd 2 = stderr, length counted by you (12, not strlen).
  • Works for any fd, including sockets (send is just the socket-flavored variant).

read — raw input

Only used in toys here; in the exam server you use recv on sockets. Same semantics: returns bytes, 0 EOF, -1 error.

sprintf — build a string in a buffer

int sprintf(char *dst, const char *fmt, ...);
  • Returns: number of chars written (excluding \0) — junk if the buffer was too small (buffer overflow, no protection!).
  • Exam patterns: sprintf(buf, "server: client %d just arrived\n", id); and, for relay, first malloc(strlen(line) + 64) then sprintf(out, "client %d: %s", id, line);
  • Trap: no size argument — always size the destination for the worst case.

4. Strings

Call Purpose Returns / traps
size_t strlen(const char *s) length without \0 UB if s is not terminated / NULL
char *strcpy(char *dst, const char *src) copy incl. \0 no bounds check
char *strcat(char *dst, const char *src) append at the end of dst dst must be big enough
int strcmp(const char *a, const char *b) compare 0 = equal
char *strstr(const char *hay, const char *needle) find substring NULL if absent — allowed in the exam but the given helpers make it unnecessary
void *memset(void *s, int c, size_t n) fill bytes the standard zeroing: memset(&addr, 0, sizeof(addr))
void bzero(void *s, size_t n) zero (legacy) same as memset(s, 0, n); the exam's main.c uses it

str_join and extract_message (given in the exam's main.c) are built from these — see architecture.md §3.6 for their contract; you don't memorize them, you copy them.


5. Memory

Call Purpose Returns / rules
void *malloc(size_t n) n uninitialized bytes NULL on failure — check it
void *calloc(size_t n, size_t size) n*size bytes, zeroed used by extract_message
void *realloc(void *p, size_t n) resize allowed, but the helpers avoid it
void free(void *p) release free(NULL) is OK; double free = UB

Ownership rule (from architecture.md §3.9): every char * handed to you by a helper is yours to free(); every client's leftover buffer is freed when the client disconnects. The leak check exists — the final reminder "Memory or fd leaks are forbidden".


6. SIGPIPE — the silent killer (know about it, don't fear it)

send on a socket whose peer reset the connection fails with EPIPE and raises SIGPIPE. Default action of SIGPIPE: kill your process. So a server can die with no message — exit code 141 (128 + 13).

  • The official test never kills a peer while messages are in flight (clients leave one by one), so passing solutions don't handle it.
  • Optional armor if you finish early:
    • send(fd, buf, len, MSG_NOSIGNAL); (Linux: suppresses SIGPIPE per call — only send is involved, which is allowed), or
    • signal(SIGPIPE, SIG_IGN); — but signal is not in the subject's allowed list, so only if your campus's grader tolerates it.
  • Diagnosing: server "mysteriously dies" → echo $? → 141.

7. Types, structs, constants

struct sockaddr_in — "an IPv4 address + port"

struct sockaddr_in {
    sa_family_t    sin_family;   /* AF_INET                */
    in_port_t      sin_port;     /* htons(port)            */
    struct in_addr sin_addr;     /* .s_addr = htonl(ip)    */
    char           sin_zero[8];  /* padding: memset it all */
};
struct in_addr { uint32_t s_addr; };

struct sockaddr — the generic type in the API

bind/accept are declared with struct sockaddr * (because C has no generics). You fill sockaddr_in and cast: (struct sockaddr *)&addr. The kernel checks sin_family to know which concrete struct you meant.

socklen_t — address length

Just an integer type for "size of that address struct" (in/out param of accept). With NULL peer you never meet it in the exam.

fd_set, FD_SETSIZE

Opaque bitmap of fds; FD_SETSIZE = 1024 = the hard ceiling for fds watched by select.

size_t vs ssize_t

size_t: unsigned count (lengths). ssize_t: signed — because results need a -1. If you print them: %zu / %zd.

Constants

Constant Meaning
AF_INET IPv4
SOCK_STREAM TCP
INADDR_ANY "bind on all interfaces" — wrong for this subject (localhost only)
2130706433 0x7F000001 = 127.0.0.1, used with htonl
FD_SETSIZE 1024
SOMAXCONN some solutions use it as backlog (180ish); 10 is fine

Byte order: htons / htonl / ntohs / ntohl

Host ↔ network byte order. Ports are 16-bit (htons), IPv4 addresses 32-bit (htonl). They are not literally in the subject's allowed list, but the exam's own main.c uses them — so they're de facto required and accepted. No ntoh* needed in this exam.


8. errno — why did it return -1?

Failing syscalls set the global int errno (#include <errno.h>). During development:

perror("bind");            /* prints: bind: Address already in use */
fprintf(stderr, "recv: %d (%s)\n", errno, strerror(errno));

perror and strerror are dev-only here (not in the exam's allowed list) — delete them before submission. The errno values you'll actually meet:

errno Means Usual appearance
EADDRINUSE address already bound bind fails — another server on the port
EBADF bad fd number closed fd still in an fd_set; select fails
EINTR interrupted by a signal select — safe to retry (continue)
EAGAIN/EWOULDBLOCK would block you called recv/send on a non-blocking fd with no readiness — in this exam: a bug in your select usage
ECONNRESET peer vanished abruptly recv/send — treat like "client left"
EPIPE peer gone send — see §6
EINVAL invalid argument nfds > FD_SETSIZE or nonsense; also listen on a bound-but-not-socket

9. Who calls whom — the exam program map

Stage (typing-script.md) Calls used
A — structs/globals/fatal write, exit, free
B — socket setup socket, memset/bzero, htons, htonl, atoi, bind, listen
C — loop + accept FD_ZERO, FD_SET, select, accept, sprintf, send
D — read path recv, strlen, str_join, extract_message, malloc, sprintf, send, free
E — disconnect sprintf, send, FD_CLR, close, free
F — grading the testers (tester/check.sh)

And the two helpers you get for free (subject/main.c): str_join, extract_message — plus that file's socket boilerplate whose calls are all in this reference.