memfd.org
← All notes

Unix / interfaces

Follow the file descriptor

Why a small integer can connect files, pipes, sockets, and the shell.

A file descriptor is a small non-negative integer in a process. It identifies an entry in that process’s descriptor table. The integer itself says very little about the object behind it.

One interface, several kinds of objects

A regular file, a pipe, and a socket can all be represented by descriptors. Not every operation makes sense for every object: seeking in a regular file is ordinary, while trying to seek in a pipe fails.

# Inspect descriptors held by your current shell.
ls -l /proc/$$/fd

# Connect one program's output to another's input.
printf 'one\ntwo\n' | wc -l

The shell does the plumbing

In the pipeline above, the shell creates a pipe and arranges descriptors before running the programs. Each program can work with standard input or standard output without knowing the command on the other end.

Close what you do not own

Descriptor leaks are resource leaks. An extra reference to a pipe’s write end can also keep a reader from observing end-of-file. Explicit ownership, close-on-exec flags, and bounded lifetimes make this kind of code easier to reason about.

← Back to the notebook