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.
| Descriptor | Name | Usual API |
|---|---|---|
| 0 | stdin | process.stdin, os.Stdin, io::stdin(), std::cin |
| 1 | stdout | console.log, fmt.Println, println!, std::cout |
| 2 | stderr | console.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.
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}`);
npx tsc --noEmit --strict main.ts && node main.ts
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.
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.
Check this idea later
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.
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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?