Updated December 1, 2026 · measured on one Linux host with one interpreter, described in Section 1; every figure below comes from it.
This page is about the descriptor table of a Linux process: one account, Python 3.12.16, the kernel in Section 1. Every number here is what that host answered, five repeats per arm. Other OSes and Windows have their own descriptor or handle tables, with their own errors; but the order in which a kernel runs its checks is that kernel’s own, so a sentence that is true here is a measurement and not a promise. Where this kernel disagreed with its own manual, Section 10 prints the disagreement instead of smoothing it over.
TL;DR
- One number, three families.
EBADFis what comes back when nothing is at the number, when the entry is open for the other direction, or when the object cannot do what was asked – and the errno cannot say which of the three it was. - The kernel reads the number, not the file. A closed descriptor answers it to a read, a stat and a duplicate alike, so no log line built from the errno alone names the family.
- The number comes back. The next open takes the closed number, and a write through the value the old owner still holds lands in the new file without an error anywhere.
- Python often answers before the kernel does. A buffered file object raises
ValueErrorwith its own message; the kernel raisesOSErrorwith the number, and the two arrive for the same mistake. - The process can keep the record the kernel does not. A tracker that checks the number and makes the call under that number’s own lock turns the 9 into a sentence, and closes the window between the check and the syscall.
- The lock has a shape it suits. Holding one number’s lock through a blocking call fits a descriptor one thread owns, or a call with a timeout; a parked socket read ends on
socket.shutdown(SHUT_RDWR), never on a local close.
Fix It First: Thirteen Changes, Matched to What You Saw
| What you saw | What the number was | Change this |
|---|---|---|
OSError: [Errno 9] Bad file descriptor from a worker, minutes into the run | Another thread closed the number first; a reissued one can even succeed against the wrong file | Close through Tracker.release, not raw os.close, and call through Tracker.call: a raw close bypasses the table (Section 10) |
ValueError: I/O operation on closed file where a 9 was expected | The file object knew before the kernel did: the closed number never reached the syscall | Trust the object: a with block keeps it closed |
socket.fileno() answers after the close instead of raising | A closed socket answers the sentinel -1, and that value names nothing | Call fileno() at the point of use and treat -1 as closed |
os.write on a file opened for reading | The number is open; the direction is wrong | Open the file with the mode the writer needs |
os.read on the write end of a pipe | Same family, the other direction | Keep the two ends apart in the code |
os.read of a directory answers 21, not 9 | The entry is fine; the object is of the wrong kind | Use os.scandir; a directory is not a file |
os.lseek on a pipe answers 29, not 9 | An object with no offset cannot be given one | Read the stream in order |
os.write to a directory answers 9, although the manual gives 21 | A directory cannot be opened for writing at all – that open answers 21 here – so its descriptor is a read-only one and the write is refused for its direction | Read the descriptor’s direction, not the sentence in the manual |
ftruncate on a read-only descriptor answers 22, although the manual gives 9 | This kernel refuses the direction as an invalid argument | Log the errno the call actually returned |
| A child process cannot use a number the parent passed in its environment | The child’s table is empty: the number names nothing there | Pass it with pass_fds or SCM_RIGHTS |
epoll.register of a closed number answers 22 instead of 9 | The number had already been handed to the epoll object itself | Register while it is open, and unregister before the close |
| A retry loop that closes a number twice | The second close is about bookkeeping, not about the file | badfd.safe_close, or let the tracker own the close |
| A shutdown that hangs: the close meant to wake a reader never returns | The reader’s call holds that number’s lock while it blocks, so the close waits behind it – and a close would not wake the read even without the lock | Wake the peer, not the number: socket.shutdown(SHUT_RDWR) from outside the lock, or a timeout on the call (Section 10) |
Two names in that table are not packages to install: badfd.guard.Tracker and badfd.safe_close are the code this page prints – badfd/guard.py for the tracker and badfd/model.py for the rule table – so both run from a copy of that tree, laid out as the appendix shows, and no pip install provides them.
1. The Denial Itself
A process does not hold files. It holds an array of pointers, and every call that takes a descriptor takes an index into that array: read(fd, buf, n) is the kernel looking up fd, finding the open file it names, and asking that file’s operations to do the work. EBADF is what comes back when one of those three steps cannot happen – there is no entry at the index, the entry is not open for this direction, or the entry’s object has no operation for this call.
That is why the message says nothing about a file. ENOENT is about a name: the path you gave does not exist. EBADF is about arithmetic inside the process: the index you gave does not name anything usable. The string the platform prints for it is Bad file descriptor, and Python wraps it in a plain OSError – not PermissionError, not FileNotFoundError, because neither permission nor existence is what was decided.
The same answer arrives from places a file-focused reader does not expect. A socket that has been closed answers it to recv; a pipe answers it to a write on the read end; an O_PATH descriptor answers it to a read, although it names a real file and fstat on it succeeds; and a number above the table’s limit answers it although the table never had an entry to lose. The kernel’s own close answers it too, when the number is not open: the only call where the answer is about the bookkeeping and never about the object.
This host is one account, uid 1000, on Linux 6.12.118-guest-1.1 with Python 3.12.16, and its descriptor table stops at 1,024 open files for this process (4,096 is the hard limit). Everything below was run there, five repeats per arm unless a row says otherwise.
Before Anything Else: which number, and what is at it
The one command that answers the question the errno refuses to answer is the kernel’s own listing of the table: ls -l /proc/PID/fd. Each line is an entry; a number that is not in the listing is not open, and the target on the right says which file the entry names. When a service logs a 9, the listing taken a second later is already the wrong listing – the number may have been reopened – so the useful habit is to log the number at the call site and compare it with the listing at the same moment.
2. Ten Numbers, Eight Calls
Two tables, one run: 10 kinds of descriptor number against 8 operations, 80 arms in all. Each arm built its own objects, made exactly one call and recorded the errno, and every arm was repeated five times with the same answer each time. Two conditions belong to the arms rather than to the kernel: the socket is non-blocking, so a read with nothing waiting answers 11 instead of waiting for a byte, and the pipe’s read end holds one byte, so its read succeeds.
The two halves are split by what the call needs from the object. A stat, a duplicate and a flag read need only the entry: they succeed on a directory, a socket and an O_PATH descriptor alike, which is why they make poor health checks. A read or a write needs the entry and a direction; a truncate needs the entry, a direction and an object that can be made shorter; a mode change needs the entry and an inode behind it.
| What is at the number | read | write | ftruncate | fchmod |
|---|---|---|---|---|
| regular file, opened read-only | 0 | 9 | 22 | 0 |
| regular file, opened write-only | 9 | 0 | 0 | 0 |
| regular file, opened read-write | 0 | 0 | 0 | 0 |
O_PATH descriptor | 9 | 9 | 9 | 9 |
| pipe, read end | 0 | 9 | 22 | 0 |
| pipe, write end | 9 | 0 | 22 | 0 |
| directory | 21 | 9 | 22 | 0 |
| socket | 11 | 0 | 22 | 0 |
| a number that was closed | 9 | 9 | 9 | 9 |
| a number never opened here | 9 | 9 | 9 | 9 |
Two cells in that table are worth stopping at, because both answer a number a manual page does not predict. A read-only regular file asked to truncate answered 22, while ftruncate(2) lists EBADF for “fd is not open for writing” – the same direction family as a refused write, spelled as an invalid argument by this kernel. A directory asked to take a write answered 9, while write(2) lists EISDIR for “fd refers to a directory”; here too the refusal is about the direction, because no descriptor for a directory ever carries write mode: the open that would add it answered 21 on this host, five times. The manual’s sentence describes a call the kernel never reaches. Every cell in the matrix has exactly one family; the number that spells it differs, and that is the reason this page keeps the family and the number apart. The table is what the host did; Section 10 is where the rule table written from the manual met it.
| What is at the number | fstat | lseek | dup | fcntl F_GETFL |
|---|---|---|---|---|
| regular file, opened read-only | 0 | 0 | 0 | 0 |
| regular file, opened write-only | 0 | 0 | 0 | 0 |
| regular file, opened read-write | 0 | 0 | 0 | 0 |
O_PATH descriptor | 0 | 9 | 0 | 0 |
| pipe, read end | 0 | 29 | 0 | 0 |
| pipe, write end | 0 | 29 | 0 | 0 |
| directory | 0 | 0 | 0 | 0 |
| socket | 0 | 29 | 0 | 0 |
| a number that was closed | 9 | 9 | 9 | 9 |
| a number never opened here | 9 | 9 | 9 | 9 |
Read together, the tables give the shape of the problem: 44 of the 80 calls succeeded, 26 answered 9, and the remaining 10 failed for another reason and answered one of 4 other numbers in all. Moving down a column from the first eight rows to the last two turns the answer to 9 without changing the call, the account or the file system: the only thing that changed is whether the entry exists.
3. Nothing There
The largest family in the matrix is the one with no entry at all: 16 of the 26 refusals came from a number that named nothing. Half of those calls used a number the arm had just closed itself and half a number that was never opened in this process, and the kernel’s answer is identical: every one of the 8 operations answered 9. A number inside the table with nothing at it and a number above the table’s limit answered the same way too (9 and 9 in Section 8), because the lookup fails at the same step in both cases.
So the number 9 tells a reader that the entry was not usable and nothing else. The four situations below produce it, and they are repaired in four different places: in the code that closed too early, in the code that never opened, in the child process that inherited a number without the file, and in the code that assumed a number would keep meaning what it meant.
| Where the 9 came from | What is at the number now | What tells them apart |
|---|---|---|
| A descriptor closed by its owner, used again | Nothing. The table slot is free and will be handed out by the next open | The value the code still holds is not the source of truth: a tracker (Section 10) or a listing of /proc/PID/fd at the call site is |
| A number never opened in this process | Nothing, and nothing ever was. A child process that received a number through an environment variable is the usual source | The child’s own listing has no entry; pass_fds or SCM_RIGHTS is the repair, not a retry |
| A number beyond the table’s limit | Nothing the table can reach: this process stops at 1,024 | The limit is the answer, and no retry will change it: the same call answered 9 for a number the table never reaches |
| A number another thread closed a moment ago | Nothing, or already something else – the slot may have been handed out again | Only the ordering tells: close and call under one lock – the tracker takes that number’s lock for both (Section 10) |
The last row is the one that produces the most confusing reports, because the same number can be free at the check and occupied at the call. Section 6 measures how often that window is hit; the honest summary here is that errno 9 from a threaded service is not evidence of a bug in the kernel, the file system or the account. It is evidence that a number was used outside the window in which its owner promised it was open.
4. The Number Came Back
A descriptor number is the lowest free slot in the array, which is exactly what makes a closed number so easy to hand back out. The probe closed a file and opened another one, five times, and the second open received the first number every time. The same happened when the second object was a socket (in each of the 5 runs), and the fstat through the old value reported a socket, because by then that is what the number named.
What makes this worse than a failed call is that the call succeeds. The stale value was used to write, the write went through in every run, and the bytes landed in the second file – STALE-WRITE at its start, every time – while the original file was left untouched in all five. Nothing in the return value, the errno or the file system’s metadata says a mistake was made.
| Scenario | What the second open received | What the stale call did |
|---|---|---|
| A file closed, then another file opened | the same number, 5 of 5 | the write succeeded and landed in the new file, in every run |
| A file closed, then a socket created | the same number, 5 of 5 | fstat through the old value reported a socket: mode changed, errno 0 |
| Three files opened together, then all closed, then one opened | the lowest of the three again, every run | nothing to see: the slot is chosen by position, not by history |
The reissue is not a privilege of files. In Section 7 the number freed by os.close was the very next number select.epoll() took, so a register call that was meant for a closed descriptor asked the epoll object to watch itself and answered 22 – a different number, from a different cause, for the same code. The same call on a number that nothing had taken since the close answered 9, which is the answer the reader expected.
The demonstration below is the whole mechanism in a dozen lines: one close, one open, one write through a value that no longer belongs to its owner. It is printed from examples/guard_demo.py, so this block is the file that ran.
"""Run the guard against the mistake it exists for, and print what each layer answered."""
from __future__ import annotations
import os
import pathlib
import tempfile
def demonstrate_reuse() -> None:
"""One close, one open, and a write through a value that no longer owns a file."""
with tempfile.TemporaryDirectory(prefix="p42_demo_") as temporary:
root = pathlib.Path(temporary)
config = root / "config.bin"
audit = root / "audit.bin"
config.write_bytes(b"config")
audit.write_bytes(b"audit")
number = os.open(config, os.O_RDONLY)
os.close(number)
again = os.open(audit, os.O_RDWR)
print(f"first number {number}, second number {again}, same: {number == again}")
os.write(number, b"STALE-WRITE")
print(f"audit.bin now starts {audit.read_bytes()[:11]!r}")
print(f"config.bin still starts {config.read_bytes()[:6]!r}")
os.close(again)
Nothing in that output is an error. The file the code meant to write was never opened at the moment of the write, and the file it did write is a different one – which is the reason a tracker is worth its microseconds in Section 9.
Two Owners of One Number
Reissue is one way to lose a number. Handing the same number to two owners is the other, and a code review misses it because both halves look correct. os.open returns a number, and open(number, "rb", closefd=True) takes that number as its own: not a duplicate, the same entry in the table. Whichever owner closes first takes the entry with it, and the other is left holding a number that names nothing.
The probe recorded both directions, five repeats each. When the file object closed the number, a stat on the raw value answered 9 in every run. When the raw os.close ran first, the object’s read answered 9 – and so did its own close, with the same 9, which is the part that hurts: the tidy-up path at the end of the request raises, in a frame that has nothing to do with the descriptor. A collected object does the same without being asked: del owner and a garbage collection closed the number, and the next stat answered 9.
The guard’s answer here is a rule rather than a check: one owner per number. Tracker.register refuses a number it already holds (ReusedDescriptor), but it cannot see inside a file object that took the same number without asking it; a record of numbers cannot decide an ownership shared behind its back, and claiming otherwise would be the kind of promise this page keeps refusing to make. The repair is the layout: a number lives in a Guarded handle or inside a file object, never in both.
When 1 Is Not stdout
The standard numbers are entries like any other. A service whose 0, 1 and 2 are closed – by its own code, or inherited closed from a supervisor – gets them handed back out to the first files it opens. The probe ran a child with the three closed and opened two files: the first was handed number 0 and the second number 1, in every run.
From that point the numbers mean something else. A log line written to number 2 answered 9, because nothing had taken that one; a line written to number 1 succeeded and landed in the second file, because by then number 1 was that file. And Python had decided at startup that its standard streams were gone: sys.stdout was None, so print() neither raised nor wrote a byte – a service that looks alive and keeps no record, which is worse than one that crashes.
The repair is to see the numbers instead of assuming them: /proc/PID/fd says what every entry names, and a supervisor that opens /dev/null on 0, 1 and 2 before it starts the program keeps the three standard numbers from being handed to a file the program opens later.
5. Whose Descriptor
A copy of the table is what fork makes. The child gets its own array, pointing at the same open files, so closing in one process does not close in the other and using a number in one does not require the other to keep it open. The 15 repeated rows behind Table 6 make that concrete: a child that closed its copy left the parent able to stat its own in every run, and a parent that closed first left the child’s inherited number working in all five.
The failure begins where the copying stops. subprocess.run starts a new program with an empty table apart from the three standard numbers, so a number passed through the environment names nothing in the child: the child’s fstat answered 9 in every row of that scenario. Passing the same number in pass_fds made the same call succeed in all five, with no change to the number: the difference was an entry in the child’s table.
| Scenario | In the parent | In the child |
|---|---|---|
| Child closes its inherited copy | its own number still worked, every run | closed, as instructed |
| Parent closes before the child uses its copy | closed | its own copy still worked, every run |
A subprocess started without pass_fds | open | nothing at the number: 9, every run |
A subprocess started with pass_fds | open | the file at the number: errno 0, every run |
This is also the reason a worker started by a preloading server can report 9 for a descriptor the master opened: the number exists in the master’s table, and the worker either inherited it at the fork or did not. When the server opens descriptors after the fork – a connection pool, a log file, a lock – the number in the log is only meaningful against the listing of the process that wrote it.
6. The Race
Two threads share one table, so a close in one is a close in the other. The probe ran the mistake deliberately: two threads calling fstat on a shared number while the main thread closed it, 500 times, 50,000 calls in all. 13,962 of those calls answered 9 – 27.9% of the calls, in 349 of the 500 runs.
The second half put the page’s tracker in place of any lock of the probe’s own: the threads called Tracker.call(number, os.fstat) and the main thread closed with Tracker.release, which takes the lock that belongs to that number. No call reached the kernel after the close – the raw errno 9 count is 0 – and the callers that arrived late were refused by the table instead, 26,829 times, with a sentence that names the descriptor and says it was closed. The lookup and the syscall are one critical section, so the window the first half measures does not exist in the second.
The difference between the two methods is the whole point of this section. Tracker.check drops the lock before the caller makes its call, so code built on the check alone reproduces the first half of Table 7 the moment another thread closes; Tracker.call holds the lock of that number until the syscall returns. A test that calls the check from one thread cannot tell the two apart, which is why this page measures the race instead of asserting it away.
| Run | Calls | Answered 9 | Refused by the table | Runs that saw a kernel 9 |
|---|---|---|---|---|
| Two threads, no lock | 50,000 | 13,962 | n/a | 349 |
| Two threads, through the tracker’s lock on that number | 50,000 | 0 | 26,829 | 0 |
The percentage is not a property of this host’s scheduler; it moves with the sleep the main thread takes before closing. What does not move is the shape: an unsynchronised close turns a fraction of the remaining calls into errno 9, and no amount of retrying distinguishes them from a number that was never open. Holding one number’s lock for the length of a blocking call is what the guarantee costs, Section 9 puts a number on that cost, and Section 10 names the two patterns the same lock rules out.
7. Three Layers in Python
Between the application and the kernel sit two objects that both keep their own idea of whether a descriptor is open. A buffered file object has a flag; a socket object has a number that it can set to nothing; and neither asks the kernel before answering. That is why the same mistake – using a number after its owner closed it – arrives as three kinds of answer. The record behind this section is 16 entry points on this host: fourteen of them were called on a number whose owner had already closed it, and the other two are the exceptions the next paragraph names. Across all sixteen, 2 raised ValueError, 11 raised OSError 9, 1 raised OSError 22, and 2 returned a value instead of raising.
The ValueError is the good outcome: the file object knows it was closed, so the call never reaches the syscall and the message says what happened – read of closed file. The OSError is the kernel’s answer arriving through Python, with the errno intact. Two rows return instead of raising: a second file.close() is a no-op because the object has already let go, and a closed socket answers its own question with a sentinel – a value that no table entry corresponds to, so it fails later, somewhere else, with errno 9.
| Called on a number whose owner had closed it | What Python did | Who noticed |
|---|---|---|
file.read() | ValueError (no errno) | the file object |
file.fileno() | ValueError (no errno) | the file object |
file.close() again | returned without raising | the file object |
os.read() | OSError 9 | the kernel |
os.close() again | OSError 9 | the kernel |
os.dup() | OSError 9 | the kernel |
select.select() | OSError 9 | the kernel |
epoll.register(), number taken since the close | OSError 22 | the epoll object, on an argument it cannot accept |
epoll.register(), number not taken since the close | OSError 9 | the kernel |
socket.recv() | OSError 9 | the kernel |
socket.send() | OSError 9 | the kernel |
socket.fileno() | returned -1 | nobody: a sentinel comes back |
socket.settimeout() | OSError 9 | the kernel |
loop.add_reader() | OSError 9 | the kernel, through the selector |
Two rows of the same record are not about a closed number and are left out of the table on purpose: os.write to a read-only descriptor, which is the direction family – a live number, refused for the mode it was opened with – and os.fstat(-1), which is not a number at all but the sentinel a closed socket answers. The counts above include them; the table prints the fourteen entry points whose owner had closed the number, so the caption and the rows agree.
The epoll pair is worth carrying into a debugging session, and so is the socket row. The pair is the same call twice, differing only in whether something had taken the number in the meantime: the taken one answered 22, the free one answered 9. And the socket row shows the other half of the problem: a sentinel returned today becomes errno 9 tomorrow, in a function that has no idea where the number came from.
8. The Numbers That Are Not 9
It helps to see what 9 is not. The probe put the same calls against objects that are open and wrong in other ways, and the kernel answered with a number chosen for the object rather than for the bookkeeping: a device with no room, a pipe or a socket with no reader, a directory read, a pipe or a socket asked to seek, a regular file asked a socket question. 7 of the 16 calls answered 9; 8 answered one of 6 other numbers, and the write to /dev/null succeeded. Seven of those eight name something the object decided; the eighth is a direction refusal, and it waits for the paragraph after Table 9 so that this list stays about the object.
| The call | The object | errno | What the number says |
|---|---|---|---|
write to a closed number | nothing at the number | 9 | Bad file descriptor |
write to a read-only descriptor | payload.bin, opened O_RDONLY | 9 | Bad file descriptor |
write to a directory | the temporary directory | 9 | Bad file descriptor |
write to /dev/full | /dev/full | 28 | No space left on device |
write to a pipe with no reader | a pipe whose read end was closed | 32 | Broken pipe |
send to a socket whose peer closed | a socketpair end | 32 | Broken pipe |
write to /dev/null | /dev/null | 0 | the call succeeded |
read a directory | the temporary directory | 21 | Is a directory |
seek a pipe | a pipe | 29 | Illegal seek |
ask a regular file a socket question | payload.bin | 88 | Socket operation on non-socket |
map a read-only descriptor for writing | payload.bin, opened O_RDONLY, mapped MAP_SHARED with PROT_WRITE | 13 | Permission denied |
read a closed number | nothing at the number | 9 | Bad file descriptor |
seek a socket | a socketpair end | 29 | Illegal seek |
stat of a number that is not open (1023) | inside the table, nothing at it | 9 | Bad file descriptor |
stat of a number that is not open (4095) | above the table's limit | 9 | Bad file descriptor |
stat of a number that is not open (50000) | above the table's limit | 9 | Bad file descriptor |
MAP_SHARED with PROT_WRITE on a read-only number).The useful split is this: errno 9 means the process asked about a number, and the answer is about the table. Most of the other numbers here mean the process asked about an object that exists and cannot do what was asked – but two of them refuse a direction, with an object quite able to comply. The 13 in Table 9 is the first, and the flags are the whole of it: the number was opened for reading, and the call mapped it with PROT_WRITE and MAP_SHARED. A shared mapping promises that the pages go back to the file, which needs a descriptor opened for writing; no permission on the path can supply that. The same number mapped MAP_PRIVATE answered 0 in every run recorded for this page, because a copy-on-write page never reaches the file, and the plain mmap.mmap call with no flags argument answered 13 – which is how this page knows that Python’s default is the shared one. The 22 that truncating a read-only file answered (Table 2, Section 2) is the second, spelled as an invalid argument by this kernel. A retry, a permission change or a different path all act on the object; none of them can repair a table entry, which is why a retry loop built on the wrong family of error spins until its budget runs out.
The same call answers 21 when the object is a directory opened for reading, 29 when the object has no offset to seek in, 28 when the device is full, 32 when the pipe has no reader left, 88 when a socket question is put to a regular file, and 13 when a read-only descriptor is mapped shared for writing. Those numbers are the kernel being helpful; 9 is the kernel being unable to be.
Three of them have a runbook of their own on this site, and the company they keep is the point. 28 is ENOSPC, in the full-device runbook: the descriptor is fine and the object has no room. 13 is EACCES, in the permission runbook: the number is fine and the permission is not. 24 is EMFILE, in the descriptor-budget runbook: too many entries in the table, which is the mirror of too few. A reader who has just been refused by one of those wants the other three at hand, because the repair each one names is in a different place in the system.
9. What It Costs
A refusal is not expensive, and the guard is not free. Eight arms, 3,000 calls each, 5 repeats, measured on this host:
| Call | Median per call | What it is |
|---|---|---|
os.write to /dev/null | 0.23 µs (0.21–0.28 µs) | the floor: one syscall that succeeds |
os.write to a closed number | 0.78 µs (0.76–0.82 µs) | the same call plus the exception: 3.4× the floor |
os.fstat on an open number | 0.78 µs (0.76–0.80 µs) | the same syscall on a live entry |
os.fstat on a closed number | 0.78 µs (0.76–0.80 µs) | no dearer than the success |
| the tracker’s check alone | 0.35 µs (0.34–0.37 µs) | added to whatever call follows: a lock and a dictionary lookup |
os.fstat through Tracker.call | 1.93 µs (1.84–1.99 µs) | the stat above plus 1.14 µs for the lookup and that number’s lock held across it |
os.write through Tracker.call | 1.40 µs (1.37–1.52 µs) | the write above plus 1.17 µs for the same two |
| the tracker’s check after the close | 0.36 µs (0.34–0.41 µs) | the same lookup deciding not to call the kernel |
The reading is a bill, not a saving. The check does not replace the syscall it protects, it is added to it: 0.35 µs on top of a write that costs 0.23 µs is more than the call’s own price. The call that holds that number’s lock across the syscall – the one without the race in Section 6 – costs 1.17 µs more than the same write made bare, which is 5.1× what the write itself costs, and 1.14 µs more than the same stat. What that buys is not speed: a 9 on a guarded path arrives before the syscall, as a sentence that names the descriptor, and the number cannot be closed between the check and the use. A path that cannot pay the lock is not a path where a cheaper check will do; it is a design where the number is not shared in the first place.
10. The Table the Process Keeps
Everything above points the same way: the kernel cannot say why a number is unusable, because by the time it looks, the reason has already happened. The process can say, because it was there. Two pieces of code are enough. The first is a rule table: for each kind of descriptor and each operation, the errno to expect and which of the three families a refusal belongs to – nothing at the number, the wrong direction, or an object of the wrong kind. It is the manual’s sentences with one cell replaced by this host’s answer, a replacement made after the matrix was measured; Table 11 and its caption say which cell, and what the agreement is with and without it. The second is an ownership table: which numbers this process holds, under which names, and whether a number it is about to use is still the one it registered.
The rule table is worth having even where the kernel corrects it, and the count has to be read in the order it happened. Of the 78 cells in Section 2 that the rules answer, 76 agreed with this kernel when the table was first written from the manual’s sentences. One cell was then changed to the kernel’s answer – a directory’s write, where write(2) promises 21 and this host answers 9 in the direction family – and with that cell the count is 77 of 78 (98.7%). The replacement is bookkeeping, not a result: it says the table was fitted to the host it was measured on, and that one part of the fit was supplied by the measurement rather than by the manual. What is left is one genuine disagreement, printed rather than smoothed over, which is the only reason to trust the rest of the count. The table prints the refusals the rules have something to say about: the 26 cells that answered 9 and the one cell that answered 22 instead.
| Cells | Calls | The rules expect | This kernel answered |
|---|---|---|---|
| Nothing at the number, both kinds | 16 | 9 | the same, on every call |
| A read or a write in the wrong direction, a directory’s write included | 5 | 9 | the same, on every call |
An O_PATH descriptor, every call but the bookkeeping ones | 5 | 9 | the same, on every call |
ftruncate on a read-only regular file | 1 | 9 | 22 |
One sentence of a manual stays outside that table, and it is worth following to the end. write(2) lists EISDIR for “fd refers to a directory”, and no caller on this kernel reaches that sentence: the write is refused for its direction before the object is ever asked, because a descriptor for a directory never carries write mode – the open that would add the mode answered 21 here too (Section 2). ftruncate(2) says EBADF for a descriptor “not open for writing”, and this kernel answers 22 – the same direction family, spelled as an invalid argument. The lesson for a runbook is not which document wins: it is that the errno must be read from the call that failed, and the family from the rules that describe it.
The second piece is smaller and more useful. It records the numbers this process opened, refuses a registration that would reuse one still held, stops a handle from reading after its number was reissued, and makes the second close a no-op instead of an exception. Each of those behaviours is exercised once in the probe that accompanies this page, and the probe’s verdict is yes for every one of them.
One method deserves its own paragraph, because it is where this version of the guard differs from the obvious one. Tracker.check looks the number up and returns; the caller then calls with nothing held, and a close from another thread can land in that gap. Tracker.call takes the function and its arguments instead, and holds the lock of that number until they return: lookup, syscall and lock release are one critical section, which is why the guarded row of Table 7 shows a kernel 9 count of zero. The lock belongs to the number rather than to the table, so a blocking read on one guarded number holds up only the other users of that same number, and the table’s own lock is held just long enough to read or change the dictionary, never across a syscall. The suite holds that behaviour with a pipe: one thread blocked inside call on the read end while another closes the write end, which a single table-wide lock would have turned into a deadlock. The price is in Table 10 – the number’s lock is held while the call runs. And the limit is stated in the code rather than left to the prose: Tracker.call cannot stop a close it never sees. A close served with os.close instead of release leaves the table saying live while the kernel says nothing there, and the tracker answers that 9 with a sentence that says so; if the number has been handed out again by then there is no 9 at all, because a write through the old handle lands in the new file. Closing through release is the caller’s half of the contract.
The same lock that removes the race also fixes what the guard is good for, and a reader should have that before building a server on it. A call holds its number’s lock for as long as it blocks, so the tracker suits a descriptor one thread owns, or calls that are non-blocking or carry a timeout. Two commoner shapes are outside it. A full-duplex socket whose reader sits in recv holds the number, so a send on the same number from another thread waits for the read to finish: the two directions take turns on one lock, which the suite pins with a stat queued behind a parked read.
And the close that is meant to end a blocked read does not end it, for two reasons a repair has to keep apart. Through release the close waits for the lock the parked call is holding, so it lands after the read rather than in it. A raw os.close() skips the lock and still does not end the read: on this kernel the close takes the number out of the table while the parked recv keeps the open file description it is using. Measured for this page, 5 of 5 closes left the reader parked, and socket.shutdown(SHUT_RDWR) ended it in 5 of 5.
Giving each direction its own number with os.dup() removes the first reason and not the second: the two numbers no longer share a lock, but 5 of 5 closes on a duplicate left a read on its twin parked, because the two numbers name one open file description. The repair is the peer’s, made from outside the lock – socket.shutdown(SHUT_RDWR) on a socket, the far end of a pipe closing, a timeout on the call, or a selector loop over non-blocking numbers. The suite pins what it can: a close on another number gets through a blocked call, a close on the same number waits, and a shutdown ends a read the tracker is holding.
The two calls are short enough to put side by side. The snippet below parks a reader in recv, closes the number under it, and then has the peer shut the connection down; it is printed from examples/socket_close_vs_shutdown.py, so this block is the function that ran.
from __future__ import annotations
import socket
import threading
import time
def main() -> int:
left, right = socket.socketpair()
reader = threading.Thread(target=left.recv, args=(1,), daemon=True)
reader.start()
time.sleep(0.2) # long enough for the read to reach the syscall
left.close() # the close, on the number the read is using
reader.join(0.5)
print(f"after close(), the reader is parked: {reader.is_alive()}")
right.shutdown(socket.SHUT_RDWR) # the peer ends its half of the connection
reader.join(0.5)
print(f"after shutdown(SHUT_RDWR), the reader is parked: {reader.is_alive()}")
right.close()
return 0
The first line it prints is True and the second is False: the close left the reader where it was, and the shutdown is what brought it back. A close speaks about this process’s own table; a shutdown is a message to the other end of the connection, which is why it reaches a call the table no longer names.
The rule table, in full
Two cells answer None rather than a number: a read from a pipe and a read from a socket depend on whether data was waiting, which is state and not shape. Naming those two as out of scope is part of the table being honest; the agreement above is counted over the 78 cells that remain. A cell of 0 is the other kind of partial answer: it says the shape check passes, not that the call returns 0, and Section 8 recorded a socket write answering 32 once its peer was gone.
"""What errno 9 is about, as a table instead of a guess.
``predict`` answers, for one operation on one kind of descriptor, the errno the manual's rules
say to expect - or ``None`` where the answer depends on state this table does not hold (whether
a pipe holds a byte, whether a socket has data). ``explain`` takes a failure that already
happened and names the family it belongs to, so a log line can say *which* of the three mistakes
produced "Bad file descriptor". ``families`` runs the other way: given only the number a log
kept, it names every family that number could have come from.
"""
from __future__ import annotations
import errno
from enum import Enum
from typing import NamedTuple
class Op(Enum):
"""The operations a descriptor number can be handed to."""
READ = "read"
WRITE = "write"
FSTAT = "fstat"
LSEEK = "lseek"
FTRUNCATE = "ftruncate"
DUP = "dup"
FCNTL = "fcntl_getfl"
FCHMOD = "fchmod"
class Kind(Enum):
"""What sits at the number: nothing, or an open file of one of eight shapes."""
READ_ONLY = "read_only"
WRITE_ONLY = "write_only"
READ_WRITE = "read_write"
PATH_ONLY = "path_only"
PIPE_READ = "pipe_read"
PIPE_WRITE = "pipe_write"
DIRECTORY = "directory"
SOCKET = "socket"
CLOSED = "closed"
NEVER_OPENED = "never_opened"
class Cause(Enum):
"""The three families behind one errno."""
NOTHING = "nothing"
DIRECTION = "direction"
KIND = "kind"
class Explanation(NamedTuple):
errno: int
cause: Cause
hint: str
_EBADF = errno.EBADF
_EISDIR = errno.EISDIR
_ESPIPE = errno.ESPIPE
_EINVAL = errno.EINVAL
# The rules, one row per kind. A cell of None is an answer this table cannot give: it depends on
# whether the object holds data at the moment of the call, which is state, not shape. A cell of 0
# says the shape check passes, not that the call returns 0: a write to a socket whose peer has
# gone answers 32, and a write to a full device answers 28, for reasons this table does not model.
#
# One cell is not the manual's: DIRECTORY's WRITE. write(2) promises EISDIR for a directory, and
# this kernel answers EBADF, because it checks the write mode of the open file before it looks at
# the object and a directory's descriptor never has that mode. The cell holds what the kernel
# did, ``cause_of`` explains why it is the direction family, and the module is printed in the
# article next to the count that keeps the correction visible.
RULES: dict[Kind, dict[Op, int | None]] = {
Kind.READ_ONLY: {Op.READ: 0, Op.WRITE: _EBADF, Op.FSTAT: 0, Op.LSEEK: 0,
Op.FTRUNCATE: _EBADF, Op.DUP: 0, Op.FCNTL: 0, Op.FCHMOD: 0},
Kind.WRITE_ONLY: {Op.READ: _EBADF, Op.WRITE: 0, Op.FSTAT: 0, Op.LSEEK: 0,
Op.FTRUNCATE: 0, Op.DUP: 0, Op.FCNTL: 0, Op.FCHMOD: 0},
Kind.READ_WRITE: {op: 0 for op in Op},
Kind.PATH_ONLY: {Op.READ: _EBADF, Op.WRITE: _EBADF, Op.FSTAT: 0, Op.LSEEK: _EBADF,
Op.FTRUNCATE: _EBADF, Op.DUP: 0, Op.FCNTL: 0, Op.FCHMOD: _EBADF},
Kind.PIPE_READ: {Op.READ: None, Op.WRITE: _EBADF, Op.FSTAT: 0, Op.LSEEK: _ESPIPE,
Op.FTRUNCATE: _EINVAL, Op.DUP: 0, Op.FCNTL: 0, Op.FCHMOD: 0},
Kind.PIPE_WRITE: {Op.READ: _EBADF, Op.WRITE: 0, Op.FSTAT: 0, Op.LSEEK: _ESPIPE,
Op.FTRUNCATE: _EINVAL, Op.DUP: 0, Op.FCNTL: 0, Op.FCHMOD: 0},
Kind.DIRECTORY: {Op.READ: _EISDIR, Op.WRITE: _EBADF, Op.FSTAT: 0, Op.LSEEK: 0,
Op.FTRUNCATE: _EINVAL, Op.DUP: 0, Op.FCNTL: 0, Op.FCHMOD: 0},
Kind.SOCKET: {Op.READ: None, Op.WRITE: 0, Op.FSTAT: 0, Op.LSEEK: _ESPIPE,
Op.FTRUNCATE: _EINVAL, Op.DUP: 0, Op.FCNTL: 0, Op.FCHMOD: 0},
Kind.CLOSED: {op: _EBADF for op in Op},
Kind.NEVER_OPENED: {op: _EBADF for op in Op},
}
HINTS = {
Cause.NOTHING: ("nothing is at this number in this process: it was closed, never opened "
"here, or belongs to another process"),
Cause.DIRECTION: ("the number is open, but not for this direction: the object was opened "
"read-only and asked to take a write, or the other way round - a "
"directory's descriptor is a read-only one too"),
Cause.KIND: ("the number is open and the direction is right, but the object does not support "
"the operation: seek on a pipe, truncate a socket, write through an O_PATH"),
}
def predict(op: Op, kind: Kind) -> int | None:
"""The errno the rules expect, or None when the answer is state-dependent."""
return RULES[kind][op]
def cause_of(op: Op, kind: Kind) -> Cause | None:
"""Why a refusal on this pair happens at all, or None when the pair is allowed."""
if kind in (Kind.CLOSED, Kind.NEVER_OPENED):
return Cause.NOTHING
if kind is Kind.PATH_ONLY and op not in (Op.FSTAT, Op.DUP, Op.FCNTL):
return Cause.KIND
if kind is Kind.READ_ONLY and op in (Op.WRITE, Op.FTRUNCATE):
# The entry is open and the object is a file: what is missing is the write direction,
# which no argument can add to a descriptor that was opened for reading.
return Cause.DIRECTION
if kind is Kind.DIRECTORY and op is Op.WRITE:
# The kernel checks the write mode of the open file before it looks at what the object
# is, and a descriptor for a directory never has that mode: the open that would give it
# one is refused (EISDIR). So the write is refused as a direction, not as a kind, and
# the manual's EISDIR sentence describes a call this kernel never reaches.
return Cause.DIRECTION
expected = RULES[kind][op]
if expected is None or expected == 0:
return None
if expected != _EBADF:
return Cause.KIND
if op in (Op.READ, Op.WRITE):
return Cause.DIRECTION
return Cause.KIND
def explain(op: Op, kind: Kind) -> Explanation | None:
"""The three fields a log line needs: the number, the family, the sentence."""
cause = cause_of(op, kind)
if cause is None:
return None
return Explanation(RULES[kind][op] or _EBADF, cause, HINTS[cause])
def families(number: int) -> tuple[Cause, ...]:
"""Every family a bare errno could belong to, when the number is all a log kept.
Nine is the one number all three families answer, so a log that kept only the errno cannot
name one of them. EINVAL covers a wrong direction on this kernel (a read-only descriptor
asked to truncate) and a wrong object on every kernel (a truncate on a pipe).
"""
if number == errno.EBADF:
return (Cause.NOTHING, Cause.DIRECTION, Cause.KIND)
if number == errno.EINVAL:
return (Cause.DIRECTION, Cause.KIND)
if number in (errno.EISDIR, errno.ESPIPE):
return (Cause.KIND,)
return ()
The ownership table, in full
One design decision is worth naming, because it is the difference between a guard that helps and one that hides the problem: when a number comes back, the old owner’s release does not close it. The descriptor at that number belongs to whoever opened it last, and a tidy-up path that closed it would take a live file away from an unrelated part of the program.
"""A table of the numbers this process owns, so "Bad file descriptor" becomes a sentence.
The kernel cannot tell a number that was closed from one that was never opened, and it cannot
tell either from a number that was closed and handed back out. All three are errno 9 at the
syscall. What separates them is bookkeeping the process itself can keep: which numbers it
registered, under which name, and whether the number it is about to use is still the one it
registered. That is all ``Tracker`` does.
tracker = Tracker()
with tracker.adopt(path, os.O_RDONLY, label="config") as handle:
handle.read(64) # the registered number, checked before the call
tracker.register(fd, "config")
os.close(fd) # the number is free again
fd = os.open(path2, os.O_RDONLY) # and the next open is handed it back
tracker.register(fd, "audit") # ReusedDescriptor: "config" still holds that number
The exception subclasses ``OSError`` with ``errno.EBADF``, so a handler written for the syscall
still catches it, while ``cause`` names the family the syscall cannot.
``check`` alone leaves a window: it drops the lock before the caller makes its call, so another
thread can close the number in between - the check-then-act race this class exists to remove.
``Tracker.call(number, function, *args)`` is the version without that window: the lookup, the
number's use and the lock's release happen in one critical section, so no ``release`` can land
between the check and the syscall. The cost is honest: a blocking call holds the lock of that
number while it blocks, so the guarantee is bought with concurrency on that one number and not
on the rest of the table.
Two locks, doing two jobs. One table-wide lock protects the dictionaries and is held only long
enough to read or change them - never across a syscall. Each number then has a lock of its own,
and ``call`` and ``release`` take only that one, so a thread blocked inside a read on one
descriptor cannot stop another thread from closing a different descriptor: the close that ends
the block still gets through.
That per-number lock is also the limit of what this tracker is for, and the limit is worth
stating in full. It suits a descriptor one thread owns, or calls that are non-blocking or carry
a timeout. Two patterns a socket server leans on are outside it. A full-duplex socket whose
reader is parked inside ``call`` on a ``recv`` holds that number's lock, so a ``send`` on the
same number from another thread waits for the read to return: the two directions serialise on
one lock. And closing the number is not the way to end a blocked read, for two separate
reasons. Through ``release`` the close waits for the lock the blocked call is holding, so it is
queued behind the read it was meant to interrupt. Even a raw ``os.close`` that skips the lock
does not end the read: the close takes the entry out of the descriptor table, while the blocked
``recv`` keeps its own reference to the open file description and stays parked until data, a
peer's end of file or a shutdown arrives. ``os.dup`` removes the first reason entirely - each
number gets a lock of its own, so the two directions stop contending at all - and leaves the
second exactly as it was, because a duplicate names the same open file description, so closing
either number leaves a read on the other parked. What ends a blocked read is the peer:
``socket.shutdown(SHUT_RDWR)`` on the socket, or the far end of a pipe closing, or a timeout, or
a selector loop over non-blocking numbers. A number that two threads drive at once in opposite
directions is not what this table models.
One rule matters more than the rest: when a number comes back, the old owner must not close it
on the way out. ``release`` on a reissued number forgets it and leaves the descriptor alone,
because the descriptor now belongs to somebody else.
What the tracker cannot see is a close that does not go through it. A caller that runs
``os.close(number)`` while the number is registered leaves the record saying *live* and the
kernel saying *nothing there*; nothing in-process can notice a syscall it never saw, because a
second ``os.close`` is indistinguishable from the first. Every number the tracker closes itself
is covered; a number closed behind its back is the caller's contract, and it has two symptoms,
not one. The loud symptom is a kernel ``EBADF`` on a number the table still lists as live - the
sentence ``StaleDescriptor`` prints for that case says exactly that. The quiet symptom is worse:
if a later ``open`` is handed that number back, the table and any handle built from it still
point at it, so a ``write`` through the old handle succeeds and lands in the new file, with no
error for anyone to catch.
"""
from __future__ import annotations
import errno
import os
import threading
from typing import Iterator
from .model import Cause, HINTS
class StaleDescriptor(OSError):
"""A call through a number this tracker no longer owns."""
cause = Cause.NOTHING
def __init__(self, number: int, label: str | None = None, detail: str | None = None) -> None:
self.number = number
self.label = label
super().__init__(errno.EBADF, self._sentence(detail))
def _sentence(self, detail: str | None) -> str:
named = f"descriptor {self.number}" + (f" ({self.label!r})" if self.label else "")
return f"{named} is not open in this tracker: {detail or HINTS[Cause.NOTHING]}"
class ReusedDescriptor(StaleDescriptor):
"""A number registered twice: the old winner's handle now addresses the new object."""
def __init__(self, number: int, label: str, previous: str) -> None:
self.previous = previous
super().__init__(number, label)
def _sentence(self, detail: str | None) -> str:
# The number is open in this tracker - under the new label - so the stale sentence
# ("not open") would be false for this case.
return (f"descriptor {self.number} came back and is now {self.label!r}: "
f"{self.previous!r} lost it when it was closed, so this handle would address "
f"the wrong object")
def _still_open(number: int) -> bool:
"""True when the kernel still has an entry at this number (a check, not a use)."""
try:
os.fstat(number)
except OSError as exc:
return exc.errno != errno.EBADF
return True
def _lost_to_a_raw_close(number: int, label: str, exc: OSError) -> StaleDescriptor:
"""The sentence for a kernel 9 on a number the table still lists as live."""
return StaleDescriptor(
number, label,
detail=("this tracker still held the number, so something closed it with os.close "
"instead of release(): a close the table cannot see"))
class Guarded:
"""One registered descriptor, used only through calls that check the table first."""
def __init__(self, tracker: "Tracker", number: int, label: str) -> None:
self.tracker = tracker
self.number = number
self.label = label
def fileno(self) -> int:
self.tracker.check(self.number)
return self.number
@property
def closed(self) -> bool:
return self.number not in self.tracker
def read(self, size: int = 65536) -> bytes:
return self.tracker.call(self.number, os.read, size)
def write(self, data: bytes) -> int:
return self.tracker.call(self.number, os.write, data)
def fstat(self) -> os.stat_result:
return self.tracker.call(self.number, os.fstat)
def lseek(self, offset: int, whence: int = os.SEEK_SET) -> int:
return self.tracker.call(self.number, os.lseek, offset, whence)
def release(self) -> bool:
"""Close once; a second call is a no-op instead of errno 9."""
return self.tracker.release(self.number)
def __enter__(self) -> "Guarded":
return self
def __exit__(self, *exc_info: object) -> None:
self.release()
def __repr__(self) -> str: # pragma: no cover - debugging aid
state = "closed" if self.closed else "open"
return f"Guarded({self.number}, {self.label!r}, {state})"
class Tracker:
"""The numbers this process owns: one lock for the table, and one lock for each number."""
def __init__(self) -> None:
self._live: dict[int, str] = {}
self._reissued: dict[int, str] = {}
self._numbers: dict[int, threading.RLock] = {}
self._lock = threading.Lock()
def __contains__(self, number: int) -> bool:
with self._lock:
return number in self._live
def __len__(self) -> int:
with self._lock:
return len(self._live)
def live(self) -> dict[int, str]:
with self._lock:
return dict(self._live)
def reissued(self) -> dict[int, str]:
with self._lock:
return dict(self._reissued)
def register(self, number: int, label: str) -> Guarded:
with self._lock:
if number in self._live:
self._reissued[number] = label
previous = self._live[number]
raise ReusedDescriptor(number, label, previous)
self._live[number] = label
self._reissued.pop(number, None)
return Guarded(self, number, label)
def adopt(self, path: str, flags: int, mode: int = 0o600, label: str | None = None) -> Guarded:
"""Open a path and register the number it came back with."""
number = os.open(path, flags, mode)
try:
return self.register(number, label or os.fspath(path))
except ReusedDescriptor:
os.close(number)
raise
def release(self, number: int) -> bool:
"""Forget the number. True when this call closed it, False when it was already gone.
A number that came back is forgotten without closing it: the descriptor at that number
belongs to whoever opened it last, and closing it here would take that away. The close
runs under the lock of ``number``, so a call already inside ``call`` on this number is
allowed to finish first and the lookup and the close keep their order. The same rule
means a release cannot interrupt a blocked call on its own number: the close is queued
behind the call, not instead of it. Nor would a close end that read if it skipped the
lock - the kernel keeps the open file description the parked call is using - so
``socket.shutdown`` is the call that ends a blocked read, not this one.
"""
with self._lock:
lock = self._number_lock(number)
with lock:
with self._lock:
if number in self._reissued:
self._reissued.pop(number, None)
self._live.pop(number, None)
return False
if number not in self._live:
return False
del self._live[number]
try:
os.close(number)
except OSError as exc:
if exc.errno != errno.EBADF:
raise
return True
def forget(self, number: int) -> bool:
"""Drop the tracker's claim on a number without touching the descriptor."""
with self._lock:
self._reissued.pop(number, None)
return self._live.pop(number, None) is not None
def _number_lock(self, number: int) -> threading.RLock:
"""The lock that belongs to one number, made once and kept.
The caller holds the table lock, and holds it only long enough to fetch this object:
no syscall runs under it. The lock outlives the registration on purpose - a number that
comes back is guarded by the same lock as before, so a caller still waiting on it and a
caller that arrives later wait on one object and not on two.
"""
lock = self._numbers.get(number)
if lock is None:
lock = threading.RLock()
self._numbers[number] = lock
return lock
def _claim(self, number: int) -> str:
"""The label this tracker holds for a number, or the exception saying why it holds none.
The caller holds the table lock; when it holds the lock of ``number`` as well, what this
decides stays true until that lock is released.
"""
label = self._live.get(number)
reissue = self._reissued.get(number)
if reissue is not None:
raise ReusedDescriptor(number, reissue, label or "unknown")
if label is None:
raise StaleDescriptor(number)
return label
def check(self, number: int) -> None:
"""Refuse a number this tracker does not hold - a check the caller then has to act on.
Between this call and the caller's own call nothing is held, so a ``release`` in
another thread can still land in that window. Where that matters, use ``call``.
"""
with self._lock:
self._claim(number)
def call(self, number: int, function, *args, **kwargs):
"""Look the number up and use it, with no window between the two.
``function`` is called as ``function(number, *args, **kwargs)`` while the lock of that
number is held, so no ``release`` from another thread can close the number after the
lookup and before the syscall. The table's own lock covers the lookup and nothing else,
so a call that blocks holds up other users of this number and no other user of the
table - including a ``release`` meant to end the block, which cannot overtake it. A
refusal the table owes the caller is raised before ``function`` runs. An
``OSError`` the kernel raises is passed through unchanged, with one exception: a 9 on a
number the kernel no longer has can only be a close this table never saw, so it is
renamed for what it is.
"""
with self._lock:
lock = self._number_lock(number)
with lock:
with self._lock:
label = self._claim(number)
try:
return function(number, *args, **kwargs)
except OSError as exc:
if exc.errno != errno.EBADF:
raise
if _still_open(number):
# The entry is there, so the 9 is the direction or the kind of the
# object. That is the caller's to read, not the tracker's to rename.
raise
raise _lost_to_a_raw_close(number, label, exc) from exc
def safe_close(number: int) -> bool:
"""Close a bare number without the errno 9 the second close would raise."""
try:
os.close(number)
except OSError as exc:
if exc.errno == errno.EBADF:
return False
raise
return True
def owned_files(directory: str) -> Iterator[int]:
"""Yield the numbers under ``directory`` this process has open - Linux only, for diagnosis."""
target = os.path.realpath(directory)
try:
names = os.listdir("/proc/self/fd")
except OSError:
return
for name in names:
try:
if os.readlink(f"/proc/self/fd/{name}").startswith(target):
yield int(name)
except OSError:
continue
Used from an application, the whole of it is one context manager and one call:
"""Run the guard against the mistake it exists for, and print what each layer answered."""
from __future__ import annotations
import os
import pathlib
import tempfile
from badfd import ReusedDescriptor, StaleDescriptor, Tracker
def usage() -> None:
"""The same mistake with the tracker in front of it."""
with tempfile.TemporaryDirectory(prefix="p42_use_") as temporary:
root = pathlib.Path(temporary)
config = root / "config.bin"
audit = root / "audit.bin"
config.write_bytes(b"config")
audit.write_bytes(b"audit")
tracker = Tracker()
handle = tracker.adopt(config, os.O_RDONLY, label="config")
number = handle.number
os.close(number)
replacement = os.open(audit, os.O_RDONLY)
try:
tracker.register(replacement, "audit")
except ReusedDescriptor as exc:
print(f"register refused: {exc}")
try:
handle.read(1)
except StaleDescriptor as exc:
print(f"read refused before the syscall: {exc}")
print(f"release of the reissued number closed nothing: {handle.release()}")
os.close(replacement)
11. Seeing It on a Host
Three commands are enough to take a report of errno 9 and turn it into a fact. The first reproduces it in the smallest possible program; the second shows the shell refusing the same thing in its own words, which is useful when the process that logged the error is already gone; the third lists the numbers a live process holds.
f=$(mktemp)
printf 'payload\n' > "$f"
python3 - "$f" <<'PY'
import os, sys
fd = os.open(sys.argv[1], os.O_RDONLY)
os.close(fd)
try:
os.read(fd, 1)
except OSError as exc:
print("after close:", exc.errno, exc.strerror, "number", fd)
PY
rm -f "$f"
The closed number prints with the errno and the message, and the program exits 0 – the point is the pair, not the failure.
f=$(mktemp)
printf 'payload\n' > "$f"
exec 3<"$f"
exec 3<&-
rm -f "$f"
cat <&3
The shell refuses the redirection before cat runs, with the same three words, and exits non-zero: the number was closed by the line above and the shell’s own table is the one being consulted.
command -v lsof >/dev/null && lsof -p $$ | head -n 3 || echo "lsof: not on this host"
ls -l /proc/$$/fd
The listing is the kernel’s answer to the question the errno refused: one line per entry, the number on the left and the file it names on the right. On a host without lsof this is the whole toolkit. Taken while the process is running, it says which numbers are open; taken after the failure, it says which ones are not – and if the number has been handed out again in between, it says that too, because the target on the right will be a file the failing code never opened. What it will not show is a number parked in a guarded read. Through release the entry stays open, because the close waits behind the call that holds the number; through a raw os.close() the entry disappears while the read is still parked, so the listing reports the number closed and the thread alive at the same moment (5 of 5 runs), and a duplicate’s number stayed listed while its twin’s read stayed parked (5 of 5). Either way the listing cannot tell a working read from a stuck one, and the call that ends one is socket.shutdown(SHUT_RDWR), not a close.
A reader on a Linux host with strace installed and ptrace permitted has a shorter path than any of these – provided the trace was already recording. A tracer attached after the failure cannot show the close that came before it, because that call has already returned: the process has to be started under the tracer, or the tracer attached while it is still healthy, and the trace kept until the 9 appears.
- Record from the start:
strace -f -e trace=%desc,%file python app.py, or attach to a running process with-p PIDbefore the request that fails.-ffollows the threads, which is usually where the close comes from. - Find the failing call. Its line carries errno 9 and the number in the argument; running the same program under
strace -Z -e trace=%desc,%fileprints only failures and makes that line easy to find, but the run without-Zis the one that holds the history. - Read the number backwards through the full trace: the
closethat freed it, theopenthat was handed it back, and the call that answered 9, each on its own line with the same number in the argument.
The failure becomes a sequence rather than a sentence. This host cannot run any of these steps – strace is not installed, and the container refuses ptrace with errno 1 under its seccomp filter (mode 2) – so the commands are printed here as the next step on a host that allows them, not as something measured on this one.
All three blocks were run exactly as printed, and the record holds the exit status and the output of each: 3 blocks, the message Bad file descriptor (yes) and the number 9 beside it (yes).
Questions This Page Answers
What does errno 9 actually mean?
That the number handed to the call did not name an open file for that operation. The kernel looks the number up in this process’s table, checks that the entry is open for the direction the call needs, and checks that the object supports the call; 9 is the answer when any of the three fails. It says nothing about the file’s existence, its permissions or its contents.
Why does Python sometimes raise ValueError instead of OSError 9?
Because a buffered file object keeps its own closed flag and checks it before the syscall. A ValueError means the object noticed; an OSError 9 means the kernel did. Both are the same mistake seen at different layers, and the ValueError is the more useful report because it names the object rather than the number.
Why is the number reused so quickly?
A descriptor number is the lowest free slot in the table, not an identity. Close one and the next open takes that slot, which is why a value kept after the close addresses a different file without any error at all. The same number came back in every run of both reuse scenarios.
How do I tell a closed number from one that was never opened?
From the errno, you cannot. Both have no entry, and both answer 9 to every operation. What separates them is the history the process holds: a tracker that registered the number, or a listing of /proc/PID/fd taken at the call site. If the number came from another process, the child’s own listing is the one that matters.
Can I just retry when I see errno 9?
No. A retry acts on the object, and 9 is about the table: the number will still name nothing on the next attempt. Reopening the file is a repair; retrying the call is a loop. The exception is a number that another thread is expected to reopen under a lock, and that is a design where the reopen and the call are both inside the lock.
Why does a child process fail with 9 for a number the parent passed?
fork copies the table and exec clears it. A subprocess starts with an empty table apart from the three standard numbers, so a number sent in an environment variable names nothing in the child. Pass it with pass_fds, or send it over a socket with SCM_RIGHTS; either way the child’s table has an entry before the number is used.
Why did epoll.register answer 22 instead of 9?
Because the number had already been handed out again – in this page’s measurement, to the epoll object itself. The register call asked the epoll to watch its own descriptor, which is an argument the object refuses. The same call on a number that nothing had taken since the close answered 9. Both rows are in the table, because both are the same bug seen at different moments.
Why does writing to a directory answer 9 while reading it answers 21?
Because the two calls are refused at different steps, and only the read gets as far as the object. A descriptor for a directory is opened read-only, and no other mode is available for it: the open that asks for write mode answers 21. So a write on that number is refused for the direction it does not have – the family a write to a read-only file belongs to – while a read carries the right direction and is then refused by the object, which is what the number 21 names.
Why is ftruncate on a read-only file 22 on this host?
Because this kernel spells a direction refusal as an invalid argument for that call. The manual page lists EBADF for a descriptor not open for writing, and the table in Section 10 records the disagreement rather than hiding it. The family is the one a refused write belongs to – the descriptor was opened for reading and cannot be made writable – which is why families names two families for the number 22: a wrong direction, and an object that cannot do the call.
Is it safe to call close twice?
The second close is refused with 9 by the kernel, so a tidy-up path that can run twice will raise. Either close in one place – the owner of the number – or wrap the close so 9 is not an error: badfd.safe_close returns false instead of raising. The dangerous case is not the second close but a close after the number came back: that one closes somebody else’s file.
Does a tracker cost too much for a hot path?
It is not free, and this page will not pretend otherwise: the check alone adds 0.35 µs to whatever call follows it, and the locked call adds 1.17 µs to a write that costs 0.23 µs (Table 10). The question is not whether the guard is cheap but whether a 9 that names nothing is acceptable on that path. Where the lock cannot be paid, the repair is to stop sharing the number, not to drop the check.
Can two objects own the same descriptor?
They can, and that is the mistake: open(number, closefd=True) takes the number os.open returned as its own, so the first close takes the entry and the other owner’s next call answers 9 – its own close included. A collected file object does the same at a moment the code does not choose. One owner per number; Tracker.register refuses a number it already holds, but it cannot see a second owner that never asked it.
Which numbers should I recognise at a glance?
Nine is the table: nothing at the number, the wrong direction, or an object of the wrong kind. Twenty-one is a directory read, twenty-nine an object with no offset, thirty-two a pipe or socket with no reader, twenty-eight a full device, eighty-eight a socket call on something that is not a socket. Those are about the object; two numbers are not. Thirteen, from mapping a read-only descriptor for writing with MAP_SHARED – MAP_PRIVATE on the same number is allowed, and the plain call takes the shared default – and twenty-two, from truncating one, are direction refusals the kernel spells in its own way, and a reader who files them under the object will look in the wrong place. Keeping the table, the object and the direction apart is what this page is built on.
Appendix: The Files This Page Prints
The package is 3 files and 504 lines; its tests are 2 files and 672 lines, and 94 of them pass. The probes that produced the records are 14 files and 1,679 lines, and they are not printed; the helper they share is, because it is the shape a reader would have to rebuild to run anything like them. Copy the folds to the paths their summaries name and run pytest badfd/tests from the directory above badfd. What this appendix makes runnable is the package, its tests and the two examples – not the measurement probes, which stay off the page.
What the package exports badfd/__init__.py
"""The two pieces this page prints: the rule table and the ownership table."""
from .guard import Guarded, ReusedDescriptor, StaleDescriptor, Tracker, safe_close
from .model import Cause, Explanation, Kind, Op, cause_of, explain, families, predict
__all__ = [
"Cause", "Explanation", "Kind", "Op", "Guarded", "ReusedDescriptor", "StaleDescriptor",
"Tracker", "safe_close", "cause_of", "explain", "families", "predict",
]
One test per family of the rule table badfd/tests/test_model.py
"""The rule table: one test per family, plus the two cells it refuses to answer."""
from __future__ import annotations
import errno
import pytest
from badfd.model import Cause, Kind, Op, cause_of, explain, families, predict
ALL_OPS = list(Op)
@pytest.mark.parametrize("op", ALL_OPS)
@pytest.mark.parametrize("kind", [Kind.CLOSED, Kind.NEVER_OPENED])
def test_nothing_at_the_number_is_ebadf_for_every_operation(kind: Kind, op: Op) -> None:
assert predict(op, kind) == errno.EBADF
assert cause_of(op, kind) is Cause.NOTHING
def test_a_read_only_descriptor_refuses_a_write() -> None:
assert predict(Op.WRITE, Kind.READ_ONLY) == errno.EBADF
assert cause_of(Op.WRITE, Kind.READ_ONLY) is Cause.DIRECTION
def test_a_write_only_descriptor_refuses_a_read() -> None:
assert predict(Op.READ, Kind.WRITE_ONLY) == errno.EBADF
assert cause_of(Op.READ, Kind.WRITE_ONLY) is Cause.DIRECTION
@pytest.mark.parametrize("op", ALL_OPS)
def test_a_read_write_descriptor_allows_every_operation(op: Op) -> None:
assert predict(op, Kind.READ_WRITE) == 0
assert cause_of(op, Kind.READ_WRITE) is None
@pytest.mark.parametrize("op", [Op.FSTAT, Op.DUP, Op.FCNTL])
def test_o_path_answers_bookkeeping_calls(op: Op) -> None:
assert predict(op, Kind.PATH_ONLY) == 0
assert cause_of(op, Kind.PATH_ONLY) is None
@pytest.mark.parametrize("op", [Op.READ, Op.WRITE, Op.LSEEK, Op.FTRUNCATE, Op.FCHMOD])
def test_o_path_refuses_everything_else(op: Op) -> None:
assert predict(op, Kind.PATH_ONLY) == errno.EBADF
assert cause_of(op, Kind.PATH_ONLY) is Cause.KIND
@pytest.mark.parametrize("kind", [Kind.PIPE_READ, Kind.PIPE_WRITE, Kind.SOCKET])
def test_seek_on_a_pipe_or_socket_is_espipe(kind: Kind) -> None:
assert predict(Op.LSEEK, kind) == errno.ESPIPE
assert cause_of(Op.LSEEK, kind) is Cause.KIND
@pytest.mark.parametrize("kind", [Kind.PIPE_READ, Kind.PIPE_WRITE, Kind.SOCKET, Kind.DIRECTORY])
def test_truncate_on_a_non_file_is_einval(kind: Kind) -> None:
assert predict(Op.FTRUNCATE, kind) == errno.EINVAL
assert cause_of(Op.FTRUNCATE, kind) is Cause.KIND
def test_a_directory_read_is_refused_with_eisdir() -> None:
assert predict(Op.READ, Kind.DIRECTORY) == errno.EISDIR
assert cause_of(Op.READ, Kind.DIRECTORY) is Cause.KIND
def test_a_directory_write_is_the_direction_family_not_the_kind_family() -> None:
"""The same sentence and the same repair as a refused write to a read-only file."""
assert predict(Op.WRITE, Kind.DIRECTORY) == errno.EBADF
assert cause_of(Op.WRITE, Kind.DIRECTORY) is Cause.DIRECTION
def test_a_read_only_descriptor_that_cannot_truncate_is_the_direction_family() -> None:
"""The manual says EBADF for this call; the family is the same as a refused write."""
assert predict(Op.FTRUNCATE, Kind.READ_ONLY) == errno.EBADF
assert cause_of(Op.FTRUNCATE, Kind.READ_ONLY) is Cause.DIRECTION
def test_an_invalid_argument_can_come_from_either_family() -> None:
"""EINVAL is the one number this page records for two families."""
assert families(errno.EINVAL) == (Cause.DIRECTION, Cause.KIND)
assert families(errno.EBADF) == (Cause.NOTHING, Cause.DIRECTION, Cause.KIND)
@pytest.mark.parametrize("pair", [(Op.READ, Kind.PIPE_READ), (Op.READ, Kind.SOCKET)])
def test_a_read_that_depends_on_buffered_data_is_out_of_scope(pair) -> None:
op, kind = pair
assert predict(op, kind) is None
assert cause_of(op, kind) is None
def test_explain_carries_the_number_the_family_and_a_sentence() -> None:
answer = explain(Op.WRITE, Kind.READ_ONLY)
assert answer is not None
assert answer.errno == errno.EBADF
assert answer.cause is Cause.DIRECTION
assert "direction" in answer.hint
def test_explain_returns_nothing_for_an_allowed_pair() -> None:
assert explain(Op.FSTAT, Kind.READ_WRITE) is None
def test_the_hint_for_nothing_mentions_the_number() -> None:
answer = explain(Op.READ, Kind.CLOSED)
assert answer is not None
assert "number" in answer.hint
@pytest.mark.parametrize("number,expected", [
(errno.EBADF, (Cause.NOTHING, Cause.DIRECTION, Cause.KIND)),
(errno.EISDIR, (Cause.KIND,)),
(errno.ESPIPE, (Cause.KIND,)),
(errno.EINVAL, (Cause.DIRECTION, Cause.KIND)),
(errno.ENOENT, ()),
(errno.EPIPE, ()),
])
def test_a_bare_errno_names_every_family_it_could_be(number: int, expected) -> None:
assert families(number) == expected
def test_every_kind_answers_every_operation() -> None:
from badfd.model import RULES
for kind in Kind:
assert set(RULES[kind]) == set(Op)
def test_the_three_families_are_distinct() -> None:
assert len({Cause.NOTHING, Cause.DIRECTION, Cause.KIND}) == 3
The ownership table, including the reissue case badfd/tests/test_guard.py
"""The ownership table: what it catches, what it stays quiet about, and what it costs."""
from __future__ import annotations
import errno
import gc
import os
import pathlib
import socket
import threading
import time
import pytest
from badfd.guard import (
Guarded,
ReusedDescriptor,
StaleDescriptor,
Tracker,
owned_files,
safe_close,
)
from badfd.model import Cause
@pytest.fixture()
def payload(tmp_path: pathlib.Path) -> pathlib.Path:
path = tmp_path / "payload.bin"
path.write_bytes(b"A" * 32)
return path
def test_register_returns_a_handle_that_names_its_number(payload: pathlib.Path) -> None:
tracker = Tracker()
number = os.open(payload, os.O_RDONLY)
handle = tracker.register(number, "payload")
try:
assert isinstance(handle, Guarded)
assert handle.number == number
assert handle.label == "payload"
assert not handle.closed
assert number in tracker
assert tracker.live() == {number: "payload"}
finally:
handle.release()
def test_release_closes_once_and_then_reports_false(payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDONLY), "payload")
assert handle.release() is True
assert handle.release() is False
assert handle.closed
assert len(tracker) == 0
def test_check_after_release_raises_with_the_number_and_the_label(payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDONLY), "config")
number = handle.number
handle.release()
with pytest.raises(StaleDescriptor) as caught:
tracker.check(number)
assert caught.value.errno == errno.EBADF
assert caught.value.number == number
assert caught.value.label is None
def test_the_exception_is_an_oserror_so_syscall_handlers_still_catch_it() -> None:
tracker = Tracker()
with pytest.raises(OSError) as caught:
tracker.check(3)
assert caught.value.errno == errno.EBADF
assert caught.value.cause is Cause.NOTHING
def test_the_message_says_what_the_number_is_not() -> None:
tracker = Tracker()
with pytest.raises(StaleDescriptor) as caught:
tracker.check(9)
text = str(caught.value)
assert "descriptor 9" in text
assert "closed" in text
def test_the_old_handle_stops_working_once_the_number_is_reissued(
payload: pathlib.Path) -> None:
tracker = Tracker()
first = os.open(payload, os.O_RDONLY)
handle = tracker.register(first, "config")
os.close(first)
second = os.open(payload, os.O_RDONLY)
with pytest.raises(ReusedDescriptor):
tracker.register(second, "audit")
with pytest.raises(StaleDescriptor):
handle.read(1)
assert tracker.reissued() == {second: "audit"}
os.close(second)
def test_release_of_a_reissued_number_does_not_close_the_new_owner(
payload: pathlib.Path) -> None:
tracker = Tracker()
first = os.open(payload, os.O_RDONLY)
handle = tracker.register(first, "config")
os.close(first)
second = os.open(payload, os.O_RDONLY)
with pytest.raises(ReusedDescriptor):
tracker.register(second, "audit")
assert handle.release() is False
assert os.fstat(second).st_size == 32
os.close(second)
def test_forget_drops_the_claim_without_closing(payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDONLY), "config")
assert tracker.forget(handle.number) is True
assert len(tracker) == 0
os.close(handle.number)
def test_a_number_that_comes_back_is_refused_as_reused(payload: pathlib.Path) -> None:
tracker = Tracker()
first = os.open(payload, os.O_RDONLY)
tracker.register(first, "config")
os.close(first)
# The kernel hands the same number straight back; the tracker still believes it owns it.
second = os.open(payload, os.O_RDONLY)
assert second == first
with pytest.raises(ReusedDescriptor) as caught:
tracker.register(second, "audit")
assert caught.value.previous == "config"
assert caught.value.label == "audit"
assert "came back" in str(caught.value)
# The number is open in the tracker under its new label, so the message must not say it
# is closed: that sentence is for the stale case, not this one.
assert "not open" not in str(caught.value)
os.close(second)
def test_reused_descriptor_is_a_stale_descriptor() -> None:
assert issubclass(ReusedDescriptor, StaleDescriptor)
def test_adopt_opens_and_registers(payload: pathlib.Path) -> None:
tracker = Tracker()
with tracker.adopt(payload, os.O_RDONLY, label="payload") as handle:
assert handle.read(4) == b"AAAA"
assert len(tracker) == 0
def test_adopt_closes_the_number_it_opened_when_registration_refuses(
payload: pathlib.Path, monkeypatch) -> None:
tracker = Tracker()
seen: list[int] = []
def refuse(number: int, label: str) -> None:
seen.append(number)
raise ReusedDescriptor(number, label, "previous")
monkeypatch.setattr(tracker, "register", refuse)
with pytest.raises(ReusedDescriptor):
tracker.adopt(payload, os.O_RDONLY)
with pytest.raises(OSError) as caught:
os.fstat(seen[0])
assert caught.value.errno == errno.EBADF
def test_guarded_read_checks_the_table_first(payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDONLY), "payload")
assert handle.read(8) == b"A" * 8
handle.release()
with pytest.raises(StaleDescriptor):
handle.read(8)
def test_guarded_write_checks_the_table_first(payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDWR), "payload")
assert handle.write(b"B") == 1
handle.release()
with pytest.raises(StaleDescriptor):
handle.write(b"B")
def test_guarded_write_on_a_read_only_number_is_the_direction_family(
payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDONLY), "payload")
with pytest.raises(OSError) as caught:
handle.write(b"B")
assert caught.value.errno == errno.EBADF
assert not isinstance(caught.value, StaleDescriptor)
handle.release()
def test_guarded_fstat_and_lseek_go_through_the_same_check(payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDWR), "payload")
assert handle.fstat().st_size == 32
assert handle.lseek(4) == 4
handle.release()
with pytest.raises(StaleDescriptor):
handle.fstat()
with pytest.raises(StaleDescriptor):
handle.lseek(0)
def test_fileno_after_release_is_an_exception_not_minus_one(payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDONLY), "payload")
handle.release()
with pytest.raises(StaleDescriptor):
handle.fileno()
def test_call_refuses_a_number_that_was_released(payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDONLY), "payload")
handle.release()
with pytest.raises(StaleDescriptor):
tracker.call(handle.number, os.fstat)
def test_call_lets_a_direction_refusal_through_as_itself(payload: pathlib.Path) -> None:
"""A live number the kernel will not write to: the 9 is about the direction, not the table."""
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDONLY), "payload")
with pytest.raises(OSError) as caught:
tracker.call(handle.number, os.write, b"B")
assert caught.value.errno == errno.EBADF
assert not isinstance(caught.value, StaleDescriptor)
handle.release()
def test_call_names_a_close_that_bypassed_the_tracker(payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDONLY), "payload")
os.close(handle.number) # not through the tracker: caller contract
with pytest.raises(StaleDescriptor) as caught:
tracker.call(handle.number, os.fstat)
assert caught.value.number == handle.number
assert "os.close" in str(caught.value)
tracker.forget(handle.number)
def test_a_write_through_a_reused_number_lands_in_the_new_file(
payload: pathlib.Path, tmp_path: pathlib.Path) -> None:
"""The quiet symptom: the close is raw, the number comes back, and the write is no error."""
tracker = Tracker()
config = os.open(payload, os.O_RDONLY)
handle = tracker.register(config, "config")
os.close(config) # not through the tracker: caller contract
audit = tmp_path / "audit.bin"
audit.write_bytes(b"")
again = os.open(audit, os.O_RDWR)
assert again == config # the kernel handed the number straight back
written = handle.write(b"STALE-WRITE") # the table still lists the number as live
assert written == 11
assert audit.read_bytes() == b"STALE-WRITE"
assert payload.read_bytes() == b"A" * 32 # the file the handle was built for is untouched
tracker.forget(again)
os.close(again)
def test_call_leaves_no_window_between_the_check_and_the_syscall(
payload: pathlib.Path) -> None:
"""Two threads call through the tracker while a third releases: no raw 9 may appear."""
leaks = 0
errors: list[BaseException] = []
for _ in range(150):
tracker = Tracker()
number = os.open(payload, os.O_RDONLY)
tracker.register(number, "payload")
start = threading.Barrier(3)
counted = {"raw": 0}
lock = threading.Lock()
def worker() -> None:
start.wait()
for _ in range(20):
try:
tracker.call(number, os.fstat)
except StaleDescriptor:
continue
except BaseException as exc: # noqa: BLE001 - counted for the assertion
with lock:
counted["raw"] += 1
errors.append(exc)
threads = [threading.Thread(target=worker) for _ in range(2)]
for thread in threads:
thread.start()
start.wait()
tracker.release(number)
for thread in threads:
thread.join()
leaks += counted["raw"]
assert leaks == 0, f"{leaks} calls reached the kernel after the close: {errors[:2]}"
def test_a_blocking_call_on_one_number_does_not_hold_up_a_close_on_another() -> None:
"""One lock per number: the read end blocked in ``call`` still lets the write end close."""
tracker = Tracker()
read_end, write_end = os.pipe()
tracker.register(read_end, "read end")
tracker.register(write_end, "write end")
answer: list[object] = []
released: list[bool] = []
entered = threading.Event()
def reader() -> None:
entered.set()
try:
answer.append(tracker.call(read_end, os.read, 16))
except BaseException as exc: # noqa: BLE001 - reported by the assertion
answer.append(exc)
def closer() -> None:
released.append(tracker.release(write_end))
reader_thread = threading.Thread(target=reader, daemon=True)
closer_thread = threading.Thread(target=closer, daemon=True)
reader_thread.start()
assert entered.wait(5)
time.sleep(0.2) # let the reader reach the syscall and block
closer_thread.start()
closer_thread.join(5)
reader_thread.join(5)
finished = not reader_thread.is_alive() and not closer_thread.is_alive()
if not finished: # undo the block: a failure must not hang pytest
os.close(write_end)
reader_thread.join(5)
closer_thread.join(5)
assert finished, "a close on one number waited for a blocking call on another number"
assert released == [True]
assert answer == [b""] # the read woke at end of file, not with a 9
tracker.release(read_end)
def test_a_close_on_the_same_number_waits_for_the_call_in_flight() -> None:
"""The same lock keeps the close out of the window: it lands after the read, not in it."""
tracker = Tracker()
read_end, write_end = os.pipe()
tracker.register(read_end, "read end")
answer: list[object] = []
released: list[bool] = []
entered = threading.Event()
def reader() -> None:
entered.set()
answer.append(tracker.call(read_end, os.read, 16))
def closer() -> None:
released.append(tracker.release(read_end))
reader_thread = threading.Thread(target=reader, daemon=True)
closer_thread = threading.Thread(target=closer, daemon=True)
reader_thread.start()
assert entered.wait(5)
time.sleep(0.2)
closer_thread.start()
time.sleep(0.2)
waited = closer_thread.is_alive() # the close is held behind the call, not inside it
os.close(write_end) # end of file: the read returns
reader_thread.join(5)
closer_thread.join(5)
assert waited, "the close did not wait for the call that held the number"
assert answer == [b""]
assert released == [True]
def test_a_second_call_on_the_same_number_waits_behind_the_blocked_one() -> None:
"""One lock per number: a stat on the number is queued behind the parked read."""
tracker = Tracker()
read_end, write_end = os.pipe()
tracker.register(read_end, "read end")
order: list[tuple[str, object]] = []
entered = threading.Event()
def reader() -> None:
entered.set()
order.append(("read", tracker.call(read_end, os.read, 16)))
def statter() -> None:
order.append(("stat", tracker.call(read_end, os.fstat)))
reader_thread = threading.Thread(target=reader, daemon=True)
stat_thread = threading.Thread(target=statter, daemon=True)
reader_thread.start()
assert entered.wait(5)
time.sleep(0.2) # the read has reached the syscall
stat_thread.start()
time.sleep(0.2)
waited = stat_thread.is_alive() # it is held behind the read, not beside it
os.write(write_end, b"Z") # the read has something to return
reader_thread.join(5)
stat_thread.join(5)
if reader_thread.is_alive() or stat_thread.is_alive(): # undo the block: never hang pytest
os.write(write_end, b"Z")
reader_thread.join(5)
stat_thread.join(5)
assert waited, "two calls on one number ran at the same time"
assert [name for name, _ in order] == ["read", "stat"]
assert order[0][1] == b"Z"
assert isinstance(order[1][1], os.stat_result)
tracker.release(read_end)
os.close(write_end) # never registered: a raw pipe end, closed raw
def test_shutdown_ends_a_read_the_tracker_is_holding() -> None:
"""A close does not end a parked read; the peer's shutdown does, and needs no lock."""
tracker = Tracker()
left, right = socket.socketpair()
number = left.fileno()
tracker.register(number, "left")
answer: list[bytes] = []
entered = threading.Event()
def reader() -> None:
entered.set()
answer.append(tracker.call(number, os.read, 16))
reader_thread = threading.Thread(target=reader, daemon=True)
reader_thread.start()
assert entered.wait(5)
time.sleep(0.2) # the read is parked, holding the number's lock
left.shutdown(socket.SHUT_RDWR) # the peer's call, made outside the lock
reader_thread.join(5)
ended = not reader_thread.is_alive()
if not ended: # a failure must not hang pytest
right.close()
reader_thread.join(5)
assert ended, "shutdown(SHUT_RDWR) did not end the blocked read"
assert answer == [b""] # end of file, not an exception
tracker.forget(number)
left.close()
right.close()
def test_two_owners_of_one_number(payload: pathlib.Path) -> None:
"""The file object closes the number itself, so the raw number is gone with it."""
number = os.open(payload, os.O_RDONLY)
owner = open(number, "rb", closefd=True)
assert owner.fileno() == number
assert owner.read(4) == b"AAAA"
owner.close()
with pytest.raises(OSError) as caught:
os.fstat(number)
assert caught.value.errno == errno.EBADF
def test_a_borrowed_number_closed_under_the_object_surfaces_as_nine(
payload: pathlib.Path) -> None:
"""The object believes it is open; its read and its tidy-up close both answer 9."""
number = os.open(payload, os.O_RDONLY)
owner = open(number, "rb", closefd=True)
os.close(number)
with pytest.raises(OSError) as caught:
owner.read(1)
assert caught.value.errno == errno.EBADF
with pytest.raises(OSError) as caught:
owner.close()
assert caught.value.errno == errno.EBADF
def test_a_collected_file_object_closes_the_borrowed_number(payload: pathlib.Path) -> None:
number = os.open(payload, os.O_RDONLY)
owner = open(number, "rb", closefd=True)
del owner
gc.collect()
with pytest.raises(OSError) as caught:
os.fstat(number)
assert caught.value.errno == errno.EBADF
def test_safe_close_is_idempotent(payload: pathlib.Path) -> None:
number = os.open(payload, os.O_RDONLY)
assert safe_close(number) is True
assert safe_close(number) is False
def test_safe_close_lets_other_errnos_through(monkeypatch) -> None:
def refuse(number: int) -> None:
raise OSError(errno.EIO, "Input/output error")
monkeypatch.setattr(os, "close", refuse)
with pytest.raises(OSError) as caught:
safe_close(3)
assert caught.value.errno == errno.EIO
def test_a_tracker_is_a_context_for_one_descriptor(payload: pathlib.Path) -> None:
tracker = Tracker()
with tracker.adopt(payload, os.O_RDONLY) as handle:
number = handle.number
assert number in tracker
assert number not in tracker
def test_live_returns_a_copy(payload: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.register(os.open(payload, os.O_RDONLY), "payload")
snapshot = tracker.live()
snapshot.clear()
assert len(tracker) == 1
handle.release()
def test_two_threads_registering_at_once_never_see_a_torn_table(payload: pathlib.Path) -> None:
tracker = Tracker()
errors: list[BaseException] = []
def worker() -> None:
try:
for _ in range(50):
number = os.open(payload, os.O_RDONLY)
tracker.register(number, "worker")
tracker.release(number)
except BaseException as exc: # noqa: BLE001 - collected for the assertion
errors.append(exc)
threads = [threading.Thread(target=worker) for _ in range(4)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
assert not errors
assert len(tracker) == 0
def test_owned_files_sees_the_numbers_under_a_directory(tmp_path: pathlib.Path) -> None:
tracker = Tracker()
handle = tracker.adopt(tmp_path / "held.bin", os.O_RDWR | os.O_CREAT)
try:
assert handle.number in set(owned_files(str(tmp_path)))
finally:
handle.release()
assert handle.number not in set(owned_files(str(tmp_path)))
def test_owned_files_skips_a_directory_that_does_not_exist() -> None:
assert list(owned_files("/nonexistent-for-this-test")) == []
The demonstration printed in Section 4 and its main examples/guard_demo.py
"""Run the guard against the mistake it exists for, and print what each layer answered."""
from __future__ import annotations
import os
import pathlib
import sys
import tempfile
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from badfd import ReusedDescriptor, StaleDescriptor, Tracker # noqa: E402
def demonstrate_reuse() -> None:
"""One close, one open, and a write through a value that no longer owns a file."""
with tempfile.TemporaryDirectory(prefix="p42_demo_") as temporary:
root = pathlib.Path(temporary)
config = root / "config.bin"
audit = root / "audit.bin"
config.write_bytes(b"config")
audit.write_bytes(b"audit")
number = os.open(config, os.O_RDONLY)
os.close(number)
again = os.open(audit, os.O_RDWR)
print(f"first number {number}, second number {again}, same: {number == again}")
os.write(number, b"STALE-WRITE")
print(f"audit.bin now starts {audit.read_bytes()[:11]!r}")
print(f"config.bin still starts {config.read_bytes()[:6]!r}")
os.close(again)
def usage() -> None:
"""The same mistake with the tracker in front of it."""
with tempfile.TemporaryDirectory(prefix="p42_use_") as temporary:
root = pathlib.Path(temporary)
config = root / "config.bin"
audit = root / "audit.bin"
config.write_bytes(b"config")
audit.write_bytes(b"audit")
tracker = Tracker()
handle = tracker.adopt(config, os.O_RDONLY, label="config")
number = handle.number
os.close(number)
replacement = os.open(audit, os.O_RDONLY)
try:
tracker.register(replacement, "audit")
except ReusedDescriptor as exc:
print(f"register refused: {exc}")
try:
handle.read(1)
except StaleDescriptor as exc:
print(f"read refused before the syscall: {exc}")
print(f"release of the reissued number closed nothing: {handle.release()}")
os.close(replacement)
def main() -> int:
demonstrate_reuse()
usage()
with tempfile.TemporaryDirectory(prefix="p42_main_") as temporary:
path = pathlib.Path(temporary) / "config.bin"
path.write_bytes(b"config")
tracker = Tracker()
handle = tracker.adopt(path, os.O_RDONLY, label="config")
print(f"opened as {handle.number}, read {handle.read(6)!r}")
print(f"first close {handle.release()}, second close {handle.release()}")
print(f"the table is empty: {len(tracker) == 0}")
try:
os.read(handle.number, 1)
except OSError as exc:
print(f"a bare read of the closed number: {exc.errno}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
The close-versus-shutdown snippet of Section 10 examples/socket_close_vs_shutdown.py
"""A close leaves a parked ``recv`` where it is; the peer's shutdown ends it."""
from __future__ import annotations
import socket
import threading
import time
def main() -> int:
left, right = socket.socketpair()
reader = threading.Thread(target=left.recv, args=(1,), daemon=True)
reader.start()
time.sleep(0.2) # long enough for the read to reach the syscall
left.close() # the close, on the number the read is using
reader.join(0.5)
print(f"after close(), the reader is parked: {reader.is_alive()}")
right.shutdown(socket.SHUT_RDWR) # the peer ends its half of the connection
reader.join(0.5)
print(f"after shutdown(SHUT_RDWR), the reader is parked: {reader.is_alive()}")
right.close()
return 0
if __name__ == "__main__":
raise SystemExit(main())
The helper every probe imports sandbox/probelib.py
"""Small helpers shared by the probes behind article 42.
Every probe writes one JSON document into ``results/``. An arm is one (kind of descriptor,
operation) pair and carries the five repeats it was run for, so a figure in the article can
always be traced back to a record rather than to a number typed into the prose.
"""
from __future__ import annotations
import json
import os
import pathlib
import statistics
RESULTS = pathlib.Path(__file__).resolve().parents[1] / "results"
def errno_of(exc: BaseException) -> int:
"""The errno an exception carries, or 0 when the call succeeded."""
return int(getattr(exc, "errno", 0) or 0)
def stats(samples: list[float]) -> dict:
numbers = [float(sample) for sample in samples]
return {
"median": statistics.median(numbers),
"min": min(numbers),
"max": max(numbers),
"mean": statistics.fmean(numbers),
}
def arm(label: str, kind: str, op: str, runs: list[dict], **extra) -> dict:
return {
"label": label,
"kind": kind,
"op": op,
"runs": runs,
"summary": {"errno": stats([int(run.get("errno") or 0) for run in runs])},
**extra,
}
def timed_arm(label: str, runs: list[dict], keys: tuple[str, ...]) -> dict:
return {
"label": label,
"runs": runs,
"summary": {key: stats([float(run[key]) for run in runs]) for key in keys},
}
def write(name: str, document: dict) -> pathlib.Path:
RESULTS.mkdir(parents=True, exist_ok=True)
path = RESULTS / name
path.write_text(json.dumps(document, indent=1, ensure_ascii=False) + "\n", encoding="utf-8")
print(f"wrote {path} ({path.stat().st_size} bytes)")
return path
def free_number(low: int = 900) -> int:
"""A descriptor number inside the table that this process is not using."""
limit = min(int(os.sysconf("SC_OPEN_MAX")), 4096)
for candidate in range(low, limit):
try:
os.fstat(candidate)
except OSError:
return candidate
raise RuntimeError("no free descriptor number found")
Going further
- Zero-Crash Python – one measured failure per issue, with its probe. Free.
- Runbook checklists on Gumroad – these tables as an incident-doc checklist.
