Skip to content
systemcoding.dev
Systems Programming

What Is a File Descriptor? stdin, stdout, stderr and the FD Table

A file descriptor is a small integer that indexes a per-process table of open files. Learn what 0, 1 and 2 mean and how open and close hand numbers out.

6 min read
Summarize in AI
Flat illustration of a hex dump with one byte highlighted, with the C, Zig and Rust logos.

Every Unix program that reads a file, prints to a terminal or talks over a socket does it through the same small thing: an integer. When open() succeeds it does not hand you a file, a struct or a pointer. It hands you a number such as 3, and from then on every read(), write() and close() takes that number. The number is a file descriptor, and understanding what it indexes explains a surprising amount of everyday behavior: why 2>&1 works, why a program that forgets to close() eventually fails, and why a child process can print into its parent's pipe. This post defines the term from scratch, shows the smallest complete program that uses descriptors directly, and ends with the rules for which number you get back.

A descriptor is an index into a table

The operating system keeps, for every process, a table of the files that process has open. A file descriptor is an index into that table. The table entries are not the files themselves: each one refers to an open file inside the kernel, and the kernel does the real work. Your program only ever holds the index, which is why the same integer type, int, covers a regular file, a terminal, a pipe and a network socket.

POSIX defines the idea precisely. In the 2024 edition of the standard, a file descriptor is a per-process, unique, non-negative integer used to identify an open file for the purpose of file access. The specification also says that valid values run from 0 up to a limit the system sets per process, which is why a descriptor is always zero or greater and why a negative return value from open() means failure rather than a valid file.

Two consequences are worth stating early. A descriptor is only meaningful inside the process that owns it, so the number 4 in one process and the number 4 in another can name entirely different files. And a descriptor is a handle, not a copy: two descriptors can refer to the same underlying open file, which later posts in this cluster call an open file description.

The three you get for free

Before your main() starts, the shell that launched your program has already arranged three descriptors, and every Unix program inherits them by convention:

NumberNameC streamNormally connected to
0standard inputstdinthe keyboard or the previous command's output
1standard outputstdoutthe terminal or the next command's input
2standard errorstderrthe terminal, kept separate from stdout

POSIX gives these fixed numbers through the macros STDIN_FILENO, STDOUT_FILENO and STDERR_FILENO, defined in <unistd.h>. The C library's stdin, stdout and stderr are FILE * streams layered on top of those descriptors, adding a buffer. When you call printf() you are writing to the stdout stream, which eventually calls write(1, ...). When you call write(1, ...) yourself you skip the buffer and the C library entirely.

Standard error is separate from standard output so that a pipeline like ./report | sort can carry data on descriptor 1 while warnings still reach a person on descriptor 2. Nothing about the kernel enforces that split. It is a convention that the shell and every well-behaved program keep.

The smallest program that uses descriptors directly

The following program never includes <stdio.h>. It writes a greeting to descriptor 1 and a complaint to descriptor 2 with the raw write() call:

hello_fd.cc
#include <string.h>
#include <unistd.h>

int main(void)
{
    const char *out = "report: 3 records\n";
    const char *err = "warning: input was empty\n";

    write(STDOUT_FILENO, out, strlen(out));
    write(STDERR_FILENO, err, strlen(err));
    return 0;
}

Built with gcc -Wall -o hello_fd hello_fd.c on GCC 14, a plain run shows both lines on the terminal, because both descriptors point at it:

Text
report: 3 records
warning: input was empty

Now redirect only descriptor 1 to a file with the shell, and the split becomes visible:

Shell
./hello_fd > out.txt
cat out.txt
Text
warning: input was empty
report: 3 records

The warning appeared on the terminal during the first command, because descriptor 2 still pointed at it. Then cat printed the file, which holds only what went to descriptor 1. The program did not change at all. The shell changed what the table entries for 1 pointed at before the program started, which is the mechanism behind every redirect, and redirecting stdout with dup2 shows how to do the same thing from C.

How open and close hand out numbers

You get a new descriptor by opening something. open() returns the lowest-numbered descriptor not currently in use by the process. POSIX states this rule directly for open(), and it applies to dup(), socket(), pipe() and the other calls that create descriptors as well. In a fresh process with 0, 1 and 2 taken, the first open() returns 3.

lowest_fd.cc
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int a = open("/etc/hostname", O_RDONLY);
    int b = open("/etc/hostname", O_RDONLY);
    printf("a=%d b=%d\n", a, b);

    close(a);
    int c = open("/etc/hostname", O_RDONLY);
    printf("after close(a): c=%d\n", c);

    close(b);
    close(c);
    return 0;
}

Assuming the program starts with only 0, 1 and 2 open, which holds when you run it from a normal shell, the output is:

Text
a=3 b=4
after close(a): c=3

The third open() reused 3 because closing a freed that slot and 3 was then the lowest free number. This "lowest available" rule is not trivia. It is what makes the classic redirection trick work: close descriptor 1, open a file, and the file lands on 1 and receives everything the program prints. It is also why a library that closes a descriptor it does not own can silently hand your next open() a number another part of the program still holds.

What the table limits

The table is finite. Each process has a soft and a hard limit on the number of open descriptors, readable with getrlimit(RLIMIT_NOFILE, ...) or the shell's ulimit -n. When a process hits the soft limit, open() fails with EMFILE, whose message reads "Too many open files". The usual cause is a loop that opens a file per iteration and never closes it, so every long-running program has to treat close() as a required half of open(). Fixing too many open files by raising RLIMIT_NOFILE walks through diagnosing it.

There is a system-wide ceiling as well, but on Linux it is rarely what stops a single program. The per-process limit is.

Descriptors beyond files

The word "file" is generous in Unix. A descriptor can name a regular file, a directory, a character device such as a terminal, a pipe, a FIFO, a socket, and on Linux also an epoll instance, a timerfd or an eventfd. They all support at least close(), and most support read() and write(), which is the reason shell pipelines and network servers can share the same plumbing. You do not choose a different integer type for a socket. You choose a different system call to create it, and the result is another entry in the same table.

The practical limit of this uniformity is that not every operation makes sense on every kind of descriptor. Calling lseek() on a pipe fails with ESPIPE, because a pipe has no position to move. A descriptor tells you where to send an operation, not which operations the target supports.

Boundaries of this model

This post describes the Unix and POSIX model, which Linux, macOS and the BSDs follow. Windows has handles instead of small integers, and the C runtime there emulates descriptors on top of them, so the numbers 0, 1 and 2 still exist in portable C code but the "lowest available" guarantee and fork() inheritance do not carry over. Everything here also assumes ordinary blocking descriptors. Non-blocking mode, O_CLOEXEC and descriptor passing are separate topics.

Share

Keep reading

Flat illustration of two options weighed side by side, with the macOS, Linux and Apple logos.
Kernels

Mach Traps vs BSD System Calls on macOS

Learn how macOS routes one trap instruction to either a Mach trap or a BSD system call, how the number sign and class decide, and why you should call libSystem.

8 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.