- Blog
- Everything Is a File Descriptor: File I/O, Offsets and Buffering on Linux
Everything Is a File Descriptor: File I/O, Offsets and Buffering on Linux
Ref
Computer Systems: A Programmer's Perspective (CS:APP), Chapter 10 — System-Level I/O
The Linux Programming Interface, Chapters 4, 5 and 13 — File I/O and File I/O Buffering
setvbuf(3) — Linux manual page
Intro
The previous post followed a C program from source file to running process. A running process that can't exchange data with the outside world isn't much use, though. It needs to read a config file, write a log, receive market data and send orders. This post covers the abstraction underneath all of that: the file descriptor.
Pipes, sockets and epoll, which later posts cover, are all built on top of file descriptors. So are several bugs that surprise even experienced programmers:
- output that appears twice after a
fork; - output that appears in a different order when you add
| cat; - data that
writereported as written but that vanishes in a power cut.
Every one of them comes down to the material in this post.
As before, everything below is real output from GCC 13.3 on Ubuntu 24.04 (x86-64).
The Problem: Too Many Kinds of "Outside"
A process might need to talk to a disk file, a terminal, a pipe to another process, a TCP connection, or a hardware device. If each needed its own API, every program would be a tangle of special cases, and you couldn't redirect a program's output from the terminal into a file without rewriting it.
Unix's answer is to make all of them look like the same thing: a stream of bytes you can read and write, referred to by a small integer. That integer is the file descriptor (fd).
This is what "everything is a file" actually means. It doesn't mean everything lives on disk. It means everything uses the same interface.
Every process starts with three fds already open: 0 is stdin, 1 is stdout, 2 is stderr. You can see a process's fd table in /proc/<pid>/fd. Here is ls looking at its own table, first in a terminal and then with stdout redirected to a file:
$ ls -l /proc/self/fd
lrwx------ 1 root root 64 Nov 23 00:37 0 -> /dev/pts/0
lrwx------ 1 root root 64 Nov 23 00:37 1 -> /dev/pts/0
lrwx------ 1 root root 64 Nov 23 00:37 2 -> /dev/pts/0
lr-x------ 1 root root 64 Nov 23 00:37 3 -> /proc/183/fd
$ ls -l /proc/self/fd > out.txt; cat out.txt
lrwx------ 1 root root 64 Nov 23 00:37 0 -> /dev/pts/0
l-wx------ 1 root root 64 Nov 23 00:37 1 -> /home/claude/stage2/out.txt
lrwx------ 1 root root 64 Nov 23 00:37 2 -> /dev/pts/0
lr-x------ 1 root root 64 Nov 23 00:37 3 -> /proc/184/fd
Redirection is just the shell pointing fd 1 somewhere else before running the program. ls itself has no idea. It writes to fd 1 exactly as it always does. (fd 3 is the /proc/self/fd directory that ls opened in order to list it.)
Three Layers Behind Every fd
An fd is only an index. Behind it sit three layers of kernel data:
per-process fd table [0] [1] [2] [3] ...
│
▼
open file description current offset, flags (O_APPEND, O_NONBLOCK...)
(system-wide) │
▼
inode the file itself: size, permissions, where the data lives
The middle layer is the one people forget, and it explains most of the surprising behaviour. Every open() call creates a new open file description. But dup(), dup2() and fork() create new fds that point at an existing one.
The offset is a cursor, and it lives in the middle layer
The offset is a cursor: the byte position where the next read or write will start. It begins at 0, and every successful read or write advances it by the number of bytes transferred. That's why you can call read in a loop and walk through a file without tracking the position yourself.
Because the offset lives in the open file description, whoever shares an open file description shares the cursor. Linux lets you watch the cursor directly: /proc/<pid>/fdinfo/<fd> begins with a pos: line. This program runs four experiments and prints pos after each one:
/* Case 1: one open(), then fork(); both processes write */
int fd = open("shared.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fork() == 0) { write(fd, "CHILD\n", 6); _exit(0); }
wait(NULL);
write(fd, "PARENT\n", 7);
/* Case 2: the same file opened twice */
int a = open("twoopen.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
int b = open("twoopen.txt", O_WRONLY);
write(a, "AAAAAAAA\n", 9);
write(b, "BBB\n", 4);
/* Case 3: same as case 2, but with O_APPEND */
a = open("append.txt", O_WRONLY | O_CREAT | O_TRUNC | O_APPEND, 0644);
b = open("append.txt", O_WRONLY | O_APPEND);
write(a, "AAAAAAAA\n", 9);
write(b, "BBB\n", 4);
/* Case 4: dup() shares the cursor, pread() ignores it */
fd = open("shared.txt", O_RDONLY);
int d = dup(fd);
read(fd, buf, 3); /* then check d's pos */
pread(fd, buf, 3, 0); /* then check fd's pos */
fork, after both fd 3 pos: 13
two opens, a fd 3 pos: 9
two opens, b fd 4 pos: 4
dup, after read(fd,3) fd 4 pos: 3
after pread fd 3 pos: 3
--- shared.txt
CHILD
PARENT
--- twoopen.txt
BBB
AAAA
--- append.txt
AAAAAAAA
BBB
Going through each case:
forkshares the cursor. The child wrote 6 bytes and moved the shared cursor to 6, so the parent's write went to 6 and the cursor ended at 13. Neither process overwrote the other.- Two
opencalls give two cursors. Both started at 0.b's 4 bytes landed on top ofa's first 4 bytes, so the file isBBB\nfollowed by the remains ofa's write. This is a real-world data-loss bug: two processes that each open the same log file withoutO_APPENDwill overwrite each other's lines. O_APPENDfixes it. With this flag, everywritemoves the cursor to the end of the file and writes there, as one atomic step. That's why many processes can safely append to one log file. (On local filesystems; NFS doesn't guarantee this.)dupshares the cursor,preadleaves it alone. Reading 3 bytes throughfdmoveddto 3 as well.pread(andpwrite) take an explicit position and neither use nor update the cursor, which lets several threads read different parts of one fd at the same time without fighting over the cursor.
lseek(fd, offset, whence) moves the cursor by hand, relative to the start (SEEK_SET), the current position (SEEK_CUR) or the end (SEEK_END). Not everything has a cursor, though. Pipes, sockets and terminals are streams: once data is read it's gone, and there's nowhere to seek to. lseek on a pipe fails:
lseek on stdin: Illegal seek # errno = ESPIPE
read and write: Two Traps
open, read, write, lseek and close look trivial. Two things about them catch nearly everyone.
Trap 1: short reads and short writes
read(fd, buf, 4096) means "read up to 4096 bytes". It returns as soon as any data is available. Here a producer writes into a pipe in pieces, and a reader calls read(0, buf, 4096) in a loop:
$ (printf 'abc'; sleep 0.2; printf 'defgh'; sleep 0.2; head -c 10000 /dev/zero) | ./reader
read() = 3
read() = 5
read() = 4096
read() = 4096
read() = 1808
read() = 0 (EOF)
The reader asked for 4096 bytes every time and got 3, then 5. That's not an error. It's just what was available. The return value means:
> 0: that many bytes were transferred, possibly fewer than you asked for.0: end of file. For a pipe, that means every write end has been closed.-1: error, details inerrno. IferrnoisEINTR, a signal interrupted the call and you should simply retry.
write can be short too, especially on pipes and sockets. So the correct way to write a buffer is a loop:
int write_all(int fd, const void *buf, size_t len) {
const char *p = buf;
while (len > 0) {
ssize_t n = write(fd, p, len);
if (n < 0) {
if (errno == EINTR) continue; /* interrupted by a signal: retry */
return -1;
}
p += n;
len -= n;
}
return 0;
}
This matters most for TCP, which is a byte stream with no message boundaries. A 300-byte message can arrive as 100 + 200, or glued together with the start of the next message. The application has to frame its own messages, typically by prefixing each one with its length.
Trap 2: blocking
By default, read on an empty pipe or socket puts the thread to sleep until data arrives. With O_NONBLOCK, it returns immediately instead:
$ (sleep 1) | ./reader nb
read() = -1, errno = Resource temporarily unavailable # EAGAIN
EAGAIN means "nothing right now, try later". Non-blocking fds are the foundation of event loops like epoll: one thread watches thousands of fds and only reads from the ones that actually have data.
Two Layers of Buffering
Here is the full path a printf takes on its way to the disk:
printf ──► [stdio buffer] ──► write() ──► [kernel page cache] ──► fsync() ──► disk
user space syscall kernel space
There are two buffers, each with a different job, and each the source of a different class of bugs.
Layer 1: the stdio buffer, which saves system calls
Every write enters the kernel, and that costs something. So printf, puts and fwrite don't call write directly. They copy into a buffer inside your process and call write only when the buffer is flushed. When it gets flushed depends on where stdout points:
- Terminal: line buffered. Flushed at every
\n, so an interactive user sees each line immediately. - File or pipe: fully buffered. Flushed when the buffer fills up (glibc uses the file's block size, usually 4096 bytes), or at
exit(). - stderr: unbuffered. Error messages appear immediately, always.
You can count the system calls. This program prints 1000 short lines:
for (int i = 0; i < 1000; i++) printf("line %d\n", i);
$ strace -c -e trace=write ./lines > f.txt # to a file
calls syscall
3 write # 4096 + 4096 + 698 bytes
$ strace -c -e trace=write ./lines | cat # to a pipe
3 write
$ strace -c -e trace=write ./lines # to a terminal
1000 write
Same program, same output, and a 333× difference in system calls depending only on where stdout points.
This one rule explains several classic surprises.
Output order changes when you add a pipe. This program alternates between stdout and stderr:
printf("1. stdout\n");
fprintf(stderr, "2. stderr\n");
printf("3. stdout\n");
fprintf(stderr, "4. stderr\n");
$ ./interleave $ ./interleave 2>&1 | cat
1. stdout 2. stderr
2. stderr 4. stderr
3. stdout 1. stdout
4. stderr 3. stdout
In a terminal, each stdout line is flushed at its \n, so the order is preserved. Through a pipe, stdout waits in the buffer until exit(), while stderr goes out immediately.
Output printed twice after fork.
printf("hello from pid %d\n", getpid());
if (fork() == 0) return 0;
wait(NULL);
$ ./forkbuf $ ./forkbuf | cat
hello from pid 254 hello from pid 256
hello from pid 256
Through a pipe, the line was still sitting in the stdio buffer when fork ran. fork copies the entire address space, buffer included, so both processes flush the same text when they exit. Both lines carry the parent's pid, which proves the child didn't print its own line. It flushed a copy of the parent's buffer. The fix is to call fflush(stdout) before fork.
Output lost with _exit. _exit skips libc's cleanup, including the flush. The previous post shows this case.
If you need different behaviour, setvbuf changes the buffering mode, fflush forces a flush, and stdbuf -o0 / stdbuf -oL change it for a program you can't recompile.
Layer 2: the page cache, which is why write doesn't mean durable
When write returns, the kernel has only copied your bytes into the page cache, the kernel's in-memory cache of file contents. The data reaches the disk later, when the kernel's writeback decides to flush it, typically within seconds. If the machine loses power before then, the data is gone, even though write returned success.
To guarantee data is on stable storage, call fsync(fd), which blocks until the device confirms the write. (fdatasync skips non-essential metadata such as timestamps. For a newly created file, you also need to fsync the parent directory to persist the directory entry.) It isn't cheap. Appending 128-byte records to a log on ext4 in a VM:
write only : 0.26 us per record
write + fsync : 186.80 us per record
That's a factor of roughly 700. It explains why databases group several transactions into one fsync (group commit), and why the setting "acknowledge a commit only after fsync" is the line between durable and fast.
The page cache also serves reads: reading a file that's already cached never touches the disk. That's why the second run of a program starts faster than the first.
Everything Is a File, Taken Seriously
Since the interface is uniform, Linux exposes kernel state as files too:
/proc: processes and kernel state./proc/<pid>/fd,/proc/<pid>/fdinfo,/proc/<pid>/maps,/proc/meminfo./sys: devices and driver settings, e.g./sys/class/net/<nic>/./dev: device files./dev/null,/dev/zero, terminals like/dev/pts/0.
All of them work with cat and echo, because they're all reached through file descriptors. Every experiment in this post that read /proc/self/fdinfo was doing exactly that.
Why This Matters for Low Latency
- Don't
writelogs on the hot path. Awriteenters the kernel, and can occasionally block behind page-cache writeback. The usual design is for the hot thread to push log records into a lock-free ring buffer, while a background thread, pinned to a non-critical core, drains it with large batched writes. - Batch with
writev. It writes several separate buffers (a header plus a body, say) in one system call, without copying them together first. - Use
O_APPENDfor shared logs,preadfor shared readers. Both avoid contention over the shared cursor. - Frame every stream. TCP gives you bytes, not messages. Every protocol parser has to handle partial reads.
Try It Yourself
ls -l /proc/self/fd, then the same with> out.txt: watch fd 1 move.cat /proc/<pid>/fdinfo/<fd>on any running process: itspos:line is the cursor.- Open the same file twice in one program and write through both fds, with and without
O_APPEND. strace -c -e trace=write ./prog > filevs./progin a terminal: count the system calls.printfa line, thenfork, and run it once in a terminal and once with| cat.- Read from a pipe fed by
(printf abc; sleep 1; printf def)and print every return value ofread.
Cheat Sheet
| Concept | What to remember |
|---|---|
| fd | Index into the per-process fd table. 0/1/2 = stdin/stdout/stderr |
| Open file description | Holds the offset and flags. Shared by dup and fork. Each open creates a new one |
| Offset | Read/write cursor. lseek moves it, O_APPEND jumps to the end atomically, pread/pwrite ignore it |
| Streams | Pipes, sockets, terminals: no offset, lseek fails with ESPIPE |
read returns | >0 bytes (maybe short), 0 EOF, -1 + errno (EINTR → retry, EAGAIN → nothing yet) |
| Short read/write | Always loop. TCP has no message boundaries |
| stdio buffering | Terminal: line. File/pipe: full (~4 KB). stderr: none |
fork + buffer | Unflushed output is copied, so it's printed twice. fflush before fork |
write returned | Data is in the page cache, not on disk |
fsync | Waits for the device. ~700× slower here. Batch it |
Wrapping Up
Four ideas cover almost all of Linux file I/O:
- One interface for everything. Files, pipes, terminals and sockets are all fds, which is why redirection works without the program knowing.
- The cursor lives in the open file description. Who shares the cursor depends on whether two fds came from one
openor two. That decides whether concurrent writers append or overwrite. readandwritecan do less than you asked. Loop, check for0and-1, and handleEINTRandEAGAIN.- There are two buffers between you and the disk. stdio saves system calls and causes the fork and ordering surprises. The page cache makes
writefast and makes it not durable until you callfsync.
The next post covers processes: why Linux creates a process by copying one with fork and then replacing it with exec, where zombie processes come from, and how signals interrupt a running program.