Skip to content

Everything is a file: descriptors and sockets

Working knowledgeUnder the hood

Files, pipes and network connections all come back from the kernel as small numbers like 3. Here is what those numbers are, the per-process table behind them, and why the same read and write work on all of them.

01 The number open() gives back

Open a file in almost any language and somewhere underneath, the kernel hands back a small integer. In Python you can see it directly:

Python
f = open("notes.txt", "w")
print(f.fileno()) # 3

Why 3, and not 0 or some address? And why do a file, a pipe and a network connection all come back as the same kind of number? That number is a file descriptor, and it is the one handle a Unix process uses for nearly everything it reads or writes. This page covers Linux; macOS and the BSDs work the same way.

02 A number is a slot in a table

The kernel keeps a small descriptor table for every process. A descriptor is just an index into it. Each slot points at a kernel record of an open file (Linux calls it a struct file), which holds the current offset and whether you opened it for reading or writing. That record in turn points at the real object: a file on disk, a pipe buffer, a socket, a terminal.

So there are three layers, and the program sees only the first:

Who holds what
LayerBelongs toHolds
Descriptor (`3`)One processA slot number in that process’s table
Open file recordThe kernelOffset, read/write mode, a pointer to the object
ObjectThe kernelThe file’s inode, a pipe buffer, a socket, a terminal

Every process starts with 0, 1 and 2 already filled in by whoever started it, usually the shell. New descriptors always take the lowest free slot, which is why your first open() returns 3.

03 What open, pipe, socket and close do

Here is one process making five calls. Watch the table, not the files.

Opening, closing and reusing descriptors
Step 1 of 6
fd table of the process
terminal0
terminal1
terminal2
–3
–4
–5
–6
–7
System calls made
Empty
  • just handed out
  • just closed
  • free slot

The program has just started. The kernel gave it three descriptors already: 0 (stdin), 1 (stdout) and 2 (stderr), all pointing at the terminal. Slots 3 onwards are free.

3 lowest free

The calls differ in what they create, but each one ends the same way: a pointer stored in a free slot, and the slot’s number returned. After that, read(fd, …), write(fd, …) and close(fd) work on any of them. That shared interface is what people mean by “everything is a file”.

04 See it yourself in /proc

On Linux, /proc/<pid>/fd lists a process’s descriptors as links to what they point at. This script makes the same calls as the trace and then lists its own table. It ran with Python 3.12 inside a python:3.12-slim container:

fd_demo.py
import os, socket
f = open("/tmp/notes.txt", "w")
print("open() ->", f.fileno())
r, w = os.pipe()
print("pipe() ->", r, w)
s = socket.socket()
print("socket() ->", s.fileno())
f.close()
g = open("/tmp/other.txt", "w")
print("after close(3), open() ->", g.fileno())
os.system(f"ls -l /proc/{os.getpid()}/fd")
Text
open() -> 3
pipe() -> 4 5
socket() -> 6
after close(3), open() -> 3
total 0
lrwx------ 1 root root 64 Nov 2 01:44 0 -> /dev/null
l-wx------ 1 root root 64 Nov 2 01:44 1 -> pipe:[1888319]
l-wx------ 1 root root 64 Nov 2 01:44 2 -> pipe:[1888320]
l-wx------ 1 root root 64 Nov 2 01:44 3 -> /tmp/other.txt
lr-x------ 1 root root 64 Nov 2 01:44 4 -> pipe:[1877837]
l-wx------ 1 root root 64 Nov 2 01:44 5 -> pipe:[1877837]
lrwx------ 1 root root 64 Nov 2 01:44 6 -> socket:[1877838]

Descriptors 4 and 5 show the same pipe:[…] number because they are two ends of one pipe. Here 0, 1 and 2 are not the terminal: the container ran without one, so Docker connected stdin to /dev/null and stdout and stderr to pipes. In an interactive shell they would show /dev/pts/0. On macOS, which has no /proc, lsof -p <pid> gives the same list.

05 Redirects and fork copy slots

Two calls copy slots instead of creating new ones. dup2(old, new) makes slot new point at the same record as old. fork() gives the child a copy of the parent’s whole table. Either way, the copies share one open file record, offset included.

After fork(): two fd tables, one shared open file (example)
Parent’s fd table
tty0
tty1
tty2
file #13
Child’s fd table (a copy)
tty0
tty1
tty2
file #13
Open files in the kernel (example)
Points toOffsetMode
#1notes.txt120write
#2terminal–read+write
  • one record, shared

Both processes’ 3 lead to the same kernel record, so they share one file offset. If either writes 10 bytes, the offset moves to 130 for both.

Shell redirects are dup2 calls made before your program starts, applied left to right. That is why the order of > and 2>&1 matters:

The same two redirects, in both orders
CommandFirstThenstderr goes to
cmd > out.txt 2>&11 → out.txt2 → copy of 1 (out.txt)out.txt
cmd 2>&1 > out.txt2 → copy of 1 (terminal)1 → out.txtthe terminal

A pipeline such as ls | wc -l is the same mechanism: the shell calls pipe(), forks twice, and in each child uses dup2 to put one end of the pipe on 1 or 0. The shell, pipes and exit codes shows that from the shell’s side.

06 Sockets: one descriptor per connection

A server has one listening socket. Each accept() returns a brand-new descriptor for that one client, so a server with 5,000 open connections holds over 5,000 descriptors. Each process has a limit on how many it may hold, shown by ulimit -n. It is often 1024 on a desktop Linux shell; containers and servers frequently raise it much higher.

Hit the limit and every call that makes a descriptor fails with EMFILE. This script opens a file 100 times without closing it, under a limit of 16:

leak.py
files = []
for i in range(100):
files.append(open("/etc/hostname"))
Shell
ulimit -n 16; python3 /leak.py
Text
Traceback (most recent call last):
File "/leak.py", line 3, in <module>
OSError: [Errno 24] Too many open files: '/etc/hostname'

Errno 24 is EMFILE. On a busy server the same error shows up as accept() failing, so new clients are refused while old ones keep working.

07 When it bites

Too many open filesLeaked descriptorsFiles or connections opened in a loop and never closed pile up until the limit is hit. Use with in Python, try-with-resources in Java, and watch the count in /proc/<pid>/fd.
read() never returns 0A pipe that never endsA reader sees end-of-file only when every write end is closed. If the parent forks a child and forgets to close its own copy of the write end, the child waits for ever.
rm big.logDeleted, but the disk is still fullRemoving a file removes its name. While any process holds a descriptor to it, the data stays on disk. lsof +L1 lists such files; restart or signal the process to let go.
O_CLOEXECDescriptors leak into child programsDescriptors survive exec() unless marked close-on-exec, so a launched program can inherit your sockets. Python and most modern runtimes set the flag by default; plain C open() does not.
close(fd); … write(fd)Writing to a reused numberAfter close, the number goes back to the pool and the next open may get it. A stale write then lands in the wrong file or socket, with no error.

A descriptor is only meaningful inside the process that owns it. Sending the number 5 to another process gives it nothing; passing a real descriptor needs fork(), or a Unix socket message with SCM_RIGHTS.

08 Check yourself

Question

A process has 0, 1, 2, 3 and 5 open. What does the next open() return?

Question

You run cmd 2>&1 > out.txt. Where does stderr go?

Question

A parent opens a file, then forks. The child writes 10 bytes through its 3. What happens to the parent’s offset on its 3?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?