~/ learn/ comp-325/ cards/ Why a TCP read must loop and a UDP read must not
1 of 10

Read exactly n bytes from a stream socket, however the kernel splits them

Read exactly n bytes from a stream socket, however the kernel splits them

Answer

size_t got = 0; while (got < n) { ssize_t k = read(fd, buf + got, n - got); if (k < 0 && errno == EINTR) continue; if (k <= 0) break; /* real error, or the peer closed */ got += (size_t)k; }

The loop is the whole point. `k` is however many bytes happened to be available; the offset `buf + got` and the shrinking count `n - got` are what make the next read append instead of overwrite. `EINTR` is a signal arriving mid-read, not a failure.

S&K 3e ch20 §20.6.4, §20.6.11; read/recv and shutdown semantics from POSIX.1-2024

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/e3e1afe9-7d76-4986-bf7e-cb2384665a70/flashcard utf-8 LF