Skip to content

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:

  • errno is meaningful only after failure. It's set by calls that return -1 (or NULL), and it's a per-thread variable — #define errno (*__errno_location()) on glibc. Checking errno when the last call succeeded reads a stale value; printing it before checking the return is a rookie tell.
  • EINTR means "a signal arrived — you decide." Slow syscalls (read on a socket, wait, poll) return it; SA_RESTART in sigaction suppresses it for most, but poll/select/nanosleep interrupt regardless.
  • EAGAIN/EWOULDBLOCK on nonblocking fds is not an error — it's "call me later." Treating it as fatal kills every event-loop-driven program.
  • close returning -1 matters on NFS and for fdatasync-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 what read/write return; comparing it to size_t re-opens the conversion bug from the integer lesson. Assign first, check < 0, then use as unsigned.
  • recv/send on sockets add MSG_NOSIGNAL to kill SIGPIPE, and send needs 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?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.