Lesson 9 of 14 · 18m
Syscalls Return Less Than You Asked: errno, EINTR, and Partial I/O
read and write return partial counts, signals interrupt slow calls with EINTR, and errno only means something after a -1.
read(fd, buf, 4096) does not read 4096 bytes. It reads up to 4096 bytes and tells you how many it got — maybe 3, maybe 2000, maybe 0 (end of file), maybe -1. The wrong mental model is that syscalls are function calls that either work or fail. They're the kernel ABI, and partial success is their normal mode: a pipe yields whatever's buffered, a socket yields whatever arrived, a signal arrives mid-call and the kernel returns EINTR so you can decide what to do. Code that treats read as all-or-nothing is wrong on every real input — it just happens to pass tests on small files.
read and write both need loops, and write needs one even on regular files (the return is a byte count, and disks full up):
/* Read exactly n bytes or fail. */
ssize_t read_n(int fd, void *buf, size_t n) {
size_t got = 0;
while (got < n) {
ssize_t r = read(fd, (char *)buf + got, n - got);
if (r < 0) {
if (errno == EINTR) continue; /* signal: retry */
return -1;
}
if (r == 0) break; /* EOF: short read, not error */
got += (size_t)r;
}
return (ssize_t)got;
}write_n is the same shape. The details that bite:
errnois meaningful only after failure. It's set by calls that return -1 (orNULL), and it's a per-thread variable —#define errno (*__errno_location())on glibc. Checkingerrnowhen the last call succeeded reads a stale value; printing it before checking the return is a rookie tell.EINTRmeans "a signal arrived — you decide." Slow syscalls (read on a socket,wait,poll) return it;SA_RESTARTinsigactionsuppresses it for most, butpoll/select/nanosleepinterrupt regardless.EAGAIN/EWOULDBLOCKon nonblocking fds is not an error — it's "call me later." Treating it as fatal kills every event-loop-driven program.closereturning -1 matters on NFS and forfdatasync-level guarantees; the man page warns that ignoring it can silently lose data. You can't always fix it, but you must log it.
The bigger discipline: every syscall's return value is load-bearing. printf-family calls return bytes written or -1; malloc returns NULL; fopen, open, fork, exec all report. fork returning -1 is the one everyone skips — the process table is a finite resource and ulimit -u/RLIMIT_NPROC will make your daemon fork-fail at exactly the load spike it exists to survive. The codebase pattern that survives audits is "check, branch, don't assume" — and strerror_r or perror for the log line, never bare errno numbers. One subtlety: strerror returns a shared static buffer (not thread-safe); strerror_r is the thread-safe variant, and its GNU version returns the message — not always your buffer — so read the return value.
Two related non-syscall traps round out the discipline: signal() vs sigaction() for handler semantics (use sigaction with SA_RESTART deliberately, since signal's restart behavior differs across unices), and stdio's buffered I/O, which hides the same partial-write reality behind fwrite's return count — check it the same way.
Try this
Write a cat clone that does one read(fd, buf, 65536); write(1, buf, 65536); — no loop. Pipe 1 MB through it (head -c 1M /dev/urandom | ./cat | wc -c) and count what survives: you get up to one chunk, not the stream. Fix it with read_n/write_n loops and re-run until wc -c agrees. Then feel EINTR for real: install a do-nothing SIGALRM handler via sigaction with sa_flags left clear of SA_RESTART, block on read(0, buf, n), and kill -ALRM the pid — read returns -1/EINTR and the loop's continue swallows it. Rebuild the handler with SA_RESTART set: the signal still fires, but the syscall resumes underneath you and EINTR never surfaces.
Field notes
ssize_t(signed) is whatread/writereturn; comparing it tosize_tre-opens the conversion bug from the integer lesson. Assign first, check< 0, then use as unsigned.recv/sendon sockets addMSG_NOSIGNALto killSIGPIPE, andsendneeds the same partial-write loop.sendfile,splice,mmap— same rule: the return value is the truth.- CS:APP's "Rio" package (
rio_readn/rio_writen) is the canonical teaching version of exactly these loops — worth reading once.
Was this lesson helpful?
Keep reading
Related articles from the SudoSecurity blog.
Implementing UART on the ATmega328P
USART on the AtMega328P Needed Documentation * Arduino Nano PCB design * Atmega328P datasheet Materials used * Arduino Nano * Arduino Uno R3 * Relevant cable * Computer Software Used * make (for easy of compiling and building) * avr-gcc (our compiler for avr ISA) *…
Hello World, Embedded Edition: Blink an LED
Embedded C: Hello WorldNeeded DocumentationArduino Nano PCB designAtmega328P datasheetMaterials usedArduino NanoArduino Uno R3Relevant cableComputerSoftware Usedmake (for easy of compiling and building)avr-gcc (our compiler for avr ISA)binutils-avravr-libcavrdude (used to flash board)The…
Build Your Own Stack-Based Bytecode Virtual Machine in C
Ever wonder how Python's CPython, the JVM, or the Lua VM actually execute code under the hood? In this article, we build a stack-based bytecode virtual machine from scratch in C.
CPPFront Project is Aiming to Modernize the C++ Language
The highly vaunted C++ language would become simpler and safer under a proposal dubbed Cppfront, an experimental C++ front end being floated by prominent C++ developer Herb Sutter. Intended as a major C++ evolution, Cppfront is an experimental “syntax 1 to syntax 2” compiler designed to explore…