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