← Runtimes
Runtimes

File descriptors and handles

Know what an open file is, and who closes it.

An open file is a live process resource whose descriptor and owner have different lifetimes.

Outcome

Explain what a file descriptor is, predict which number an open receives, route output to the right standard stream, and make sure every descriptor a program opens is closed on every path.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

File descriptor
A small non-negative integer that indexes this process’s table of open files, pipes, sockets and devices. Each system call on an open file takes it.
Standard streams
The conventional descriptors 0 (stdin), 1 (stdout) and 2 (stderr). The launcher normally arranges them, but it can leave them closed or redirect them.
Owning handle
A value responsible for an open resource: for example Go’s os.File, Rust’s File, C++’s fstream or Node’s FileHandle. Explicit close and automatic scope cleanup are different lifetime policies.
Leak
A descriptor the program no longer needs but never closes. It occupies a slot until the process exits.
EMFILE
The error an open returns when the process reaches its descriptor limit. The configured limit varies by system and process.
try/finally
A finally block runs after its try block however that block ends: normally, by return or by throw.

The resource behind a handle

When open succeeds, the kernel creates an entry for the open file and returns a descriptor: an index into this process’s table. Later read, write and close calls pass that number. The number means nothing outside this process, and once it is closed it can be handed out again.

A library can wrap that number in an owning handle, a value responsible for releasing the resource. Copying a descriptor number does not create another owner or extend the resource’s lifetime. Whether a native handle closes automatically depends on its type and cleanup policy; finishing a read is a separate event.

01The descriptor table

An open file is a number in your process’s table

A batch summarizer works through the first few hundred files and then every open fails with “too many open files”, although each file is read only once. What is an open file to the program, and why does it stay open?

The batch summarizer’s output is consumed as data, so missing-file warnings must not become result rows. Launchers normally arrange descriptors 0, 1 and 2 as standard input, output and error, although they can be redirected or closed. With stderr still attached to the terminal, program > results.txt captures result rows while warnings stay visible.

What a process starts with
DescriptorNameUsual API
0stdinprocess.stdin, os.Stdin, io::stdin(), std::cin
1stdoutconsole.log, fmt.Println, println!, std::cout
2stderrconsole.error, fmt.Fprintln(os.Stderr, …), eprintln!, std::cerr

02Which number?

The lowest free number is reused

Before repairing the leak, check what an open owns. This reduced probe opens two files, closes the first and opens again. Assume the opens succeed and no other code changes the available descriptor slots during those operations. The printed numbers distinguish a process-local slot from the file’s identity.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { closeSync, openSync, writeFileSync } from 'node:fs';

writeFileSync('/tmp/a.txt', 'a');
writeFileSync('/tmp/b.txt', 'b');

const first = openSync('/tmp/a.txt', 'r');
const second = openSync('/tmp/b.txt', 'r');
closeSync(first);
const third = openSync('/tmp/b.txt', 'r');

console.log(`first=${first} second=${second} third=${third}`);
console.log(`third reused first's number: ${third === first}`);
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts
The program opens a.txt, then b.txt, closes a.txt and opens b.txt again. What number does the third open receive?

03Who closes it?

Some handles close themselves; raw numbers never do

The input loop finishes reading each file, but that alone does not say who releases its descriptor. Check how the selected native represents the open file before choosing the summarizer’s cleanup boundary.

A loop runs 10,000 times. Each iteration calls fs.openSync(path, "r") and reads the file with fs.readFileSync(fd) and does nothing else with it. What happens to the process’s descriptor table?

04Practice

Summarize without leaking

The lab continues the summarizer. First separate result rows from missing-file diagnostics, then release files after normal summaries. Finally reject unsupported headers and malformed count metadata without retaining open files on either path. Linux /proc/self/fd reports live descriptors whose targets are inside the lab directory; stdout and stderr are checked separately. This observes descriptors in the running process, not a modeled OS table.

The batch summarizer

A summarizer opens input files and reports their item counts while Linux reports which lab files it still holds open. Send diagnostics to stderr, stop leaking descriptors, then close them on every way out of a summary.

  1. easy · R-FD-V4-1 Report on the right stream
  2. medium · R-FD-V4-2 Close what you open
  3. hard · R-FD-V4-3 Close on every path
Check this idea later
A CLI prints its CSV result and occasional warnings. A user runs it as tool > out.csv. Where should the warnings go so out.csv stays valid?
A service fails with EMFILE after several hours. Its file count grows by one per request. What is the right first fix?
A logger saves descriptor 7, closes it during rotation, then opens a database file. A delayed write uses the saved 7. Where can those bytes go?
Sources
In the frontend Trace the owner in an incomplete server handler. Optional

This deliberately incomplete handler is under review for a report dashboard. Follow the FileHandle after a successful JSON response and after JSON parsing throws. Which owner still accounts for it when the request ends? The framework’s request lifetime does not automatically supply a deterministic close.

app/api/summary/route.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { open } from 'node:fs/promises';

export const runtime = 'nodejs';

export async function GET() {
  const file = await open('/srv/reports/latest.json', 'r');
  const text = await file.readFile('utf8');
  const summary = JSON.parse(text);

  return Response.json(summary);
}

The App Router handler selects Node for its filesystem API. Both a successful return and a read/parse exception leave this code without an explicit close of the opened FileHandle. A request finishing and the file owner releasing its resource are distinct events; garbage-collection timing is not a close guarantee.

Sources: Node.js: FileHandle close,Next.js: Route Handlers,SvelteKit: server routes.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.