Linux System Programming · intermediate · ~10 min

open / read / write / close

Use the four core POSIX I/O syscalls.

Lesson

open(path, flags, [mode]) returns an fd or -1. read(fd, buf, n) and write(fd, buf, n) return the number of bytes transferred (which may be less than nshort reads/writes are the norm). close(fd) releases the descriptor.

Always loop short writes; always check return values; always handle EINTR (a signal interrupted the syscall — retry).

Code examples

ssize_t write_all(int fd, const void *buf, size_t n) {
    const char *p = buf; size_t left = n;
    while (left) {
        ssize_t w = write(fd, p, left);
        if (w < 0) { if (errno == EINTR) continue; return -1; }
        p += w; left -= (size_t)w;
    }
    return (ssize_t)n;
}

Common mistakes

  • Treating partial writes as errors. Loop until done.