Experiments and implementations · Intermediate

Observing file-descriptor reuse

Observe reuse of a closed file-descriptor number and distinguish an integer handle from the lifetime and identity of an open file.

Ask Logeia about this articleTry the three questionsReview your answers

Updated

On this page
  1. A descriptor number is not a permanent file identity
  2. Compare two opens rather than assuming descriptor three
  3. Do not operate through a stale integer
  4. Distinguish a new open from duplication
  5. Do not turn one ordering into a concurrency guarantee
  6. Ask Logeia about this articleCheck your understanding

A descriptor number is not a permanent file identity

On Linux, open returns the lowest-numbered descriptor that is currently unused by the process. A descriptor is an entry point for an open file, not a permanent identity that remains attached after closing. If a background operation remembers only an integer after its owner closes it, a later open may assign that integer to an unrelated file. The background operation could then access the wrong target. Demonstrate reuse with a small single-threaded program and temporary files created by the experiment itself. Do not inspect or manipulate another process’s descriptors. The controlled example isolates handle lifetime without relying on a concurrent race to happen by chance.

Compare two opens rather than assuming descriptor three

The program opens a.txt, stores its descriptor, writes and closes it. It then opens b.txt without an intervening open in the same single-threaded process. The returned number is reused, while the new write changes b.txt rather than a.txt. TemporaryDirectory confines the experiment and cleans up the created files. Each descriptor also has a finally block for closing on exceptional paths. Compare the two returned values instead of hard-coding the number three. A program can inherit additional open descriptors when it starts, so the first available number depends on its environment. The controlled ordering, rather than a universal starting integer, explains the expected equality.

python
import os, pathlib, tempfile
with tempfile.TemporaryDirectory() as folder:
    a, b = (pathlib.Path(folder) / name for name in ('a.txt', 'b.txt'))
    first = os.open(a, os.O_CREAT | os.O_WRONLY, 0o600)
    try:
        os.write(first, b'alpha')
    finally:
        os.close(first)
    second = os.open(b, os.O_CREAT | os.O_WRONLY, 0o600)
    try:
        assert second == first
        os.write(second, b'beta')
    finally:
        os.close(second)
    assert a.read_bytes() == b'alpha' and b.read_bytes() == b'beta'
    print(first, second, 'reused with a different target')

Do not operate through a stale integer

Using an integer after closing its descriptor is not reliably rejected. Before reuse it may produce EBADF; after reuse it can refer to a new open file. Do not demonstrate this by accidentally closing or writing through a stale owner. The example deliberately uses only descriptors returned by currently successful opens. In an application, establish ownership and keep the resource alive until dependent operations finish. An explicit duplicate descriptor can be appropriate when separate ownership is required, but merely copying the integer into another variable does not duplicate the kernel reference. A lifecycle bug is therefore possible even when every integer has a plausible small value and the operating-system call itself succeeds.

Distinguish a new open from duplication

Opening the same pathname twice generally creates separate open file descriptions with separate offsets. A duplicated descriptor instead refers to the same open file description and shares its offset. Both arrangements expose two integers, so the variable representation alone does not identify which state is shared. A follow-up experiment can compare the first character read through two independent opens with consecutive reads through a descriptor and its duplicate. Keep that as a separate property test. Observing number reuse after close does not establish offset sharing. The construction of the handles and the precise observation determine the conclusion, not only the equality or inequality of their integer labels.

Do not turn one ordering into a concurrency guarantee

No other thread or library operation opens a file between the two controlled opens here. In a real application another operation can consume the newly available descriptor first, so immediate reuse by the next visible open is not a universal scheduling guarantee. A run without reuse also does not prove that a stale-handle bug is safe. Review the relationship between closing, asynchronous completion and exceptional cleanup. Checking whether a descriptor appears valid before using it introduces another interval in which ownership can change; extra probes alone do not solve lifetime management. A production solution needs an ownership and synchronization contract that keeps the intended resource available for the entire operation.

Reading and practice are recorded separately in this browser, for each language.

Learn this in order

Understand the systems behind the web · STEP 14

Choose a learning path