TL;DR
- A Linux pipe holds 65,536 bytes, and every failure here is that number arriving unnoticed: a child that fills its second pipe blocks forever while the parent waits on the first (1.01 s of silence), and a parent that calls
wait()without reading never gets an exit status at all. - Three fixes cover it: read both pipes at once (
communicate()), start the child in its own session and signal the group on a deadline, and reap every child. Measured: a 2 MiB capture in 19.6 ms, a timed-out tree empty 6.0 ms after the group signal, and 20 un-waited children cleared by onepoll()each. - The runner in section 14 does all three, feeds stdin from a thread, caps what it keeps and ships with 60 tests. When a pipe is the wrong tool,
/dev/nulltook 15.5 ms for 32 MiB, and a death signal removed a grandchild in 1.2 ms.
What this runbook covers
- What was measured, on what, and what was not
- Seven ways a subprocess call fails
- The 64 KiB pipe, measured three ways
- The read order that deadlocks
- wait() with the pipes left full
- Zombies: a process nobody reaps
- Timeouts that kill the child and leave the tree
- Process groups, and the six milliseconds it takes
- What a full pipe costs the writer
- A bigger pipe
- Which reader, and which read size
- Who keeps the pipe open
- asyncio: three descriptors per child
- The module: procguard, its bugs, and its sixty tests
- The cheapest fix, and the ones outside Python
- The production runbook
- What to put on a dashboard
- Frequently asked questions
- What was verified, and what is out of scope
- Keep reading on TechBobby
1. What was measured, on what, and what was not
A subprocess call has no slow path that shows up in a profile. It either returns in microseconds or it never returns, and the difference is usually a byte count nobody counted: the bytes a pipe will hold, the bytes a child writes before the parent starts reading, and the processes a signal actually reaches. Every figure in this article came from running the failure on this machine and reading the result out of /proc, a pipe, or a clock.
The host is one container: 2 vCPUs on an Intel(R) Xeon(R) Platinum 8488C, 1,486 MiB of RAM of which 314 MiB was available, Linux 6.12.8+, CPython 3.12.16. Its /proc shows only the container’s own process tree (2 processes at the start), and an orphan here stays a zombie instead of being reaped, which is worth knowing before section 7: the leftovers of an aborted tree are visible rather than invisible. That is a property of this namespace, not of Linux in general, and it is the one place where a production host will look better than these tables.
| Item | Measured value | How it was read |
|---|---|---|
| Kernel | 6.12.8+ on x86_64 | uname -a |
| CPU | Intel(R) Xeon(R) Platinum 8488C, 2 vCPUs | /proc/cpuinfo |
| Memory | 1,486 MiB total, 314 MiB available | /proc/meminfo |
| Python | 3.12.16, CPython | platform.python_version() |
| Pipe maximum | 1,048,576 bytes | /proc/sys/fs/pipe-max-size |
| Default socket buffer | 212,992 bytes | /proc/sys/net/core/wmem_default |
| Clock | 1 ns resolution | time.get_clock_info('perf_counter') |
| Timer tick | 100 Hz | os.sysconf('SC_CLK_TCK') |
| Descriptors at start | 4 | /proc/self/fd |
| Process table | 2 visible processes | the container’s own namespace |
Three kinds of probe appear below. The first drives a real child and measures the parent: how many bytes a read returned, how long a call sat still, what /proc/<pid>/status said while it sat. The second measures the pipe itself, by filling a non-blocking descriptor until the kernel refuses. The third measures the module this article publishes, running the same failures against it so that the fix is compared with the problem on the same host in the same hour. Every number on the page is rendered from the JSON those probes write, and a token that does not exist stops the build. The probes depend on one helper file and nothing else outside the standard library: every name a block uses and does not define is imported from that file, so the file printed below plus any single block has everything that block needs. The child sources are constants in the same file, for the same reason.
A block of that file is a set of definitions, not a script: executing it creates the functions and returns, and the probe itself is the entry function its file calls from if __name__ == "__main__": at its end – main() in every probe but the two asyncio ones, whose entry point is run_probe(). So the way to run a block on its own is to save it beside common.py, import it as a module and call the function that returns the record – or to add that same one-line guard to the block. The article’s build check does exactly this: it proves each block is a verbatim slice of its file, executes it as printed, and reports which blocks only define names and which run something when executed. Table 19 in section 19 lists that per block.
"""Helpers shared by the probes: where results go, how /proc is read, and the children.
This is the whole file. Every probe block in the article imports what it uses from
here and nothing else outside the standard library, so this file beside one printed
block supplies every name that block does not define. A block is a set of
definitions rather than a script: to run one, import it as a module and call its
function, or add the same one-line ``__main__`` guard each probe file ends with.
"""
from __future__ import annotations
import json
import os
import pathlib
import sys
import time
HERE = pathlib.Path(__file__).resolve().parent
RESULTS = HERE.parent / "results"
PY = sys.executable
PYTHON = PY # the name the older probes use for the same path
MIB = 1 << 20
MARKER = "procguard-grandchild"
# The tag the grandchild writes into its own /proc/<pid>/comm. Nine bytes, because the
# kernel keeps at most fifteen there: MARKER itself is truncated to "procguard-grand".
ROLE_TAG = "prcgrd-gc"
GRANDCHILD_SLEEP = 8.0
# A child that fills both pipes: 64 KiB to each, sixteen times over, then exits.
CHILD = """
import os, sys
chunk = b"o" * 65536
for _ in range(16):
os.write(1, chunk)
os.write(2, chunk)
sys.exit(0)
"""
# A child that starts a grandchild and then waits. The grandchild either inherits
# our pipe (inherit) or has its own descriptors pointed at /dev/null. It renames
# itself to ROLE_TAG before it sleeps, so the tag identifies it and nothing else -
# a tag placed in this source would also be in this process's own command line.
SPAWNER = """
import subprocess, sys, time
inherit = {inherit!r}
child = subprocess.Popen(
[sys.executable, "-c", "import time\\nopen('/proc/self/comm','w').write('{role}')\\ntime.sleep({sleep})"],
stdout=None if inherit else subprocess.DEVNULL,
stderr=None if inherit else subprocess.DEVNULL,
stdin=None if inherit else subprocess.DEVNULL)
print(child.pid, flush=True)
time.sleep(120)
"""
def write_result(name: str, payload: dict) -> dict:
"""Write one probe's measurements as JSON, which is what the article renders."""
RESULTS.mkdir(exist_ok=True)
path = RESULTS / name
path.write_text(json.dumps(payload, indent=1, sort_keys=True) + "\n", encoding="utf-8")
print(f"wrote {path} ({path.stat().st_size} bytes)")
return payload
def status_fields(pid: int) -> dict[str, str]:
"""The fields of /proc/<pid>/status, as the kernel reports them."""
try:
text = pathlib.Path(f"/proc/{pid}/status").read_text()
except (FileNotFoundError, ProcessLookupError):
return {}
fields: dict[str, str] = {}
for line in text.splitlines():
key, _, value = line.partition(":")
if value:
fields[key] = value.strip()
return fields
def child_io(pid: int) -> dict[str, int]:
"""The counters of /proc/<pid>/io: rchar, wchar and the byte counts beneath them."""
table: dict[str, int] = {}
try:
for line in pathlib.Path(f"/proc/{pid}/io").read_text().splitlines():
key, _, value = line.partition(":")
table[key] = int(value)
except (FileNotFoundError, ProcessLookupError):
return {}
return table
def pids_of(marker: str) -> list[int]:
"""Every process whose command line contains `marker` (probe children)."""
found = []
for entry in pathlib.Path("/proc").iterdir():
if not entry.name.isdigit():
continue
try:
cmdline = pathlib.Path(f"/proc/{entry.name}/cmdline").read_bytes()
except (FileNotFoundError, ProcessLookupError):
continue
if marker.encode() in cmdline:
found.append(int(entry.name))
return sorted(found)
def zombies() -> list[int]:
"""Every pid in state Z, which is a process nobody has waited for."""
return sorted(int(entry.name) for entry in pathlib.Path("/proc").iterdir()
if entry.name.isdigit()
and status_fields(int(entry.name)).get("State", "").startswith("Z"))
def own_zombies() -> list[int]:
"""Zombie children of this process, by /proc/<pid>/status."""
mine = []
for entry in pathlib.Path("/proc").iterdir():
if not entry.name.isdigit():
continue
table = status_fields(int(entry.name))
if table.get("State", "").startswith("Z") and table.get("PPid") == str(os.getpid()):
mine.append(int(entry.name))
return sorted(mine)
def inode_of(fd: int) -> str:
"""The inode of a pipe, taken from the target of /proc/self/fd/<fd>."""
target = os.readlink(f"/proc/self/fd/{fd}")
return target.split("[", 1)[1].rstrip("]") if "[" in target else target
def fields(pid: int) -> dict[str, str | None]:
"""The status fields a process report quotes, in one call."""
table = status_fields(pid)
return {key: table.get(key) for key in ("Name", "State", "PPid", "Threads", "VmRSS")}
def spawner(inherit: bool) -> list[str]:
"""The argv of a ready-to-time-out tree, with the grandchild's pipe inherited or not."""
return [PY, "-c", SPAWNER.format(inherit=inherit, sleep=GRANDCHILD_SLEEP, role=ROLE_TAG)]
def pids_with_comm(name: str) -> list[int]:
"""Processes whose /proc/<pid>/comm is exactly `name` - a tag they set themselves."""
found = []
for entry in pathlib.Path("/proc").iterdir():
if not entry.name.isdigit():
continue
try:
comm = pathlib.Path(f"/proc/{entry.name}/comm").read_text().strip()
except (FileNotFoundError, ProcessLookupError, OSError):
continue
if comm == name:
found.append(int(entry.name))
return sorted(found)
def grandchild_pids() -> list[int]:
"""The grandchild alone, found by the tag it wrote into its own comm."""
return pids_with_comm(ROLE_TAG)
def watch_grandchild(stop) -> dict:
"""Poll for the grandchild while the parent is stuck, recording when it lived.
The grandchild is identified by ROLE_TAG in its own comm, not by a tag in a
command line. A tag passed through the spawner's ``-c`` source is also in the
spawner's own command line, and a scan for it returns the spawner first - the
earlier version of this probe did exactly that, and ``03_timeout.py`` measures
the trap with a tree of its own. ``cmdline_matches`` and
``marker_in_parent_cmdline`` record what a scan for MARKER finds here: nothing,
because this spawner's source does not carry it.
"""
first_seen = None
last_seen = None
pid = None
ppid = None
cmdline_matches = 0
marker_in_parent_cmdline = None
while not stop.is_set():
found = grandchild_pids()
if found and first_seen is None:
first_seen = time.perf_counter()
pid = found[0]
ppid = status_fields(pid).get("PPid")
if ppid is not None:
try:
parent = pathlib.Path(f"/proc/{ppid}/cmdline").read_bytes()
except (FileNotFoundError, ProcessLookupError):
parent = b""
marker_in_parent_cmdline = MARKER.encode() in parent
if found:
last_seen = time.perf_counter()
cmdline_matches = max(cmdline_matches, len(pids_of(MARKER)))
time.sleep(0.025)
return {"first_seen": first_seen, "last_seen": last_seen, "pid": pid, "ppid": ppid,
"cmdline_matches": cmdline_matches,
"marker_in_parent_cmdline": marker_in_parent_cmdline}
def members(pgid: int) -> list[int]:
"""Live pids in this process group, read from /proc/<pid>/stat (zombies excluded)."""
found = []
for entry in pathlib.Path("/proc").iterdir():
if not entry.name.isdigit():
continue
try:
text = pathlib.Path(f"/proc/{entry.name}/stat").read_text()
except (FileNotFoundError, ProcessLookupError):
continue
tail = text[text.rfind(")") + 2:].split()
try:
if int(tail[2]) != pgid or tail[0] == "Z":
continue
except (IndexError, ValueError):
continue
found.append(int(entry.name))
return sorted(found)
def wait_until_empty(pgid: int, timeout_s: float) -> float:
"""Seconds until no non-zombie process remains in the group.
The zombie of the direct child stays in the group until it is reaped, so the
wait watches for the group to empty of live processes, listed fresh each poll.
"""
started = time.perf_counter()
while time.perf_counter() - started < timeout_s:
if not members(pgid):
return time.perf_counter() - started
time.sleep(0.005)
return time.perf_counter() - started
__all__ = [
"RESULTS", "PY", "PYTHON", "MIB", "MARKER", "ROLE_TAG", "GRANDCHILD_SLEEP", "CHILD",
"SPAWNER", "write_result", "status_fields", "child_io", "pids_of", "pids_with_comm",
"grandchild_pids", "zombies", "own_zombies", "inode_of", "fields", "spawner",
"watch_grandchild", "members", "wait_until_empty",
]
Each probe is a file that writes one JSON record; the article reads values out of those records and never types a figure by hand. Where a probe needs a child it takes the child’s source from that same helper file and runs it with the interpreter path it imports, so the child in the measurement is a real Python process on the same kernel, not a mock.
Out of scope: HTTP, TLS, containers, cgroups, systemd unit behaviour, shell=True quoting, Windows handles and job objects, macOS, Python versions before 3.12, kernel patches that change pipe accounting, and every mechanism that depends on a specific init system are out of scope. So is the parent’s own I/O scheduler: everything here is a pipe on local disk with nothing else running except the probe.
2. Seven ways a subprocess call fails
“Deadlock” is used for seven different failures with seven different fixes, and the first ten minutes of an incident are usually spent deciding which one it is. The matrix below is the one this article works from: the shape of the failure, what the operator sees, the mechanism underneath, and the cheapest measurement that separates it from the others. Each row is measured in the section named beside it.
| Shape | What you see | The mechanism | Measured evidence | Section |
|---|---|---|---|---|
| hang | The call never returns, the child is alive, CPU is idle | Two pipes, read in sequence: the child fills the second while the parent waits on the first for an EOF that cannot arrive | 131,072 bytes read, then 1.01 s of silence, child asleep in write | Section 4 |
| hang | wait() never returns, the child is still alive | The child is blocked in its last write and cannot exit; the parent waits for an exit that cannot happen. Same cause as the row above, seen from the other side | wait still blocked after 1.5 s, child blocked with 0 bytes written | Section 5 |
| orphan | A timeout fires and the service keeps working – on the wrong work | The signal reaches one process; grandchildren keep running and keep the pipe open | return in 1.00 s, 1 survivor | Section 7 |
| leak | The process table fills with Z entries, pids run out | Nobody calls waitpid: the exit status is kept for a parent that never asks | 20 zombies from 20 un-waited children | Section 6 |
| self-signal | A kill in an exception handler takes the worker down with it – not a hang: one signal ends both processes | The child shares the caller’s process group, so a group signal is a signal to self | child pgid 0 equals the caller’s 0 | Section 8 |
| descriptor | A closed child still holds a descriptor, or the parent hits its limit | Descriptors follow the child’s lifetime, and a grandchild that inherited one extends that lifetime past the child | 307 descriptors for 100 live children, 5 buffers read before an async stall | Sections 12 and 13 |
| latency | The write path is slow although the reader is idle – not a hang either, just a call that waits for a buffer slot | A blocking write returns only when it has written all of it, so its cost is the reader’s pace | 81.9 ms inside one 204,800-byte write | Section 9 |
/proc.Two of the seven carry the label hang in the first column, and they are the ones this article spends most of its length on: the call does not come back. Both share a single cause – a pipe nobody drains – and they are listed apart because the code that produces them looks nothing alike: one reads the wrong pipe first, the other never reads at all and calls wait(). The other five are not hangs, which is why each carries its own label: a timeout leaves an orphan writing to a pipe nobody can close, a child nobody waits for stays a zombie, a shared process group ends the worker with a signal, a descriptor outlives the child that held it, and a full pipe only slows the writer down. Keeping all seven in one table is useful because they arrive through the same door – a subprocess call that did not behave – and because telling them apart is the first step of the runbook in section 16.
The article follows the order of those rows, from the cheapest thing to check to the most expensive thing to discover: capacity first, because every other number is a multiple of it; read order next, because it is the bug most often written by hand; then zombies and process groups, which are what a timeout leaves behind; then the write path, the pipe size and draining; and asyncio last, with the same failures wearing different names.
One convention: a difference smaller than the spread between two runs of the same probe is reported as flat. Where that happened – chunk size, the reading method in section 11 – the article says so instead of ranking noise, and every table that compares runs prints the individual runs beside the median so the reader can check the claim.
3. The 64 KiB pipe, measured three ways
The number that every other section multiplies is the pipe buffer. On Linux it is a page count, not a byte count: the default is sixteen pages, and on a 4,096-byte page that is 65,536 bytes. The kernel will say so if asked, but the interesting measurement is the empirical one, because it is the number the child actually experiences – and because a pipe whose size was changed by F_SETPIPE_SZ or by a container’s tuning will not match the default anyone remembers.
The probe opens a pipe, sets the write end non-blocking, and writes until the kernel refuses. With 1-byte writes that is 65,536 syscalls and 65,536 bytes; with 4,096-byte writes it is 16 syscalls and the same 65,536 bytes. The second fill on the same descriptor accepts 0 bytes, which is the definition of full. Five repetitions at each of four write sizes all returned the same total, so the figure is not an average.
from __future__ import annotations
import os
import time
def fill_until_eagain(fd: int, chunk: int) -> dict:
"""Write into a non-blocking pipe until it refuses, counting the bytes."""
os.set_blocking(fd, False)
payload = b"x" * chunk
total = 0
writes = 0
refused = 0
started = time.perf_counter()
while True:
try:
total += os.write(fd, payload)
writes += 1
except BlockingIOError as exc:
refused = exc.errno
break
return {"bytes": total, "writes": writes, "chunk": chunk, "errno": refused,
"seconds": round(time.perf_counter() - started, 6)}
def capacity_trials(chunk: int, trials: int = 5) -> dict:
counts = []
for _ in range(trials):
read_fd, write_fd = os.pipe()
try:
counts.append(fill_until_eagain(write_fd, chunk)["bytes"])
finally:
os.close(read_fd)
os.close(write_fd)
return {"chunk": chunk, "trials": counts, "bytes": min(counts), "stable": len(set(counts)) == 1}
A pipe that subprocess hands a child is the same pipe: filling the stdin of a sleeping child took 64 writes of 1 KiB and stopped at 65,536 bytes, matching what F_GETPIPE_SZ declared for that descriptor.
| Measurement | Bytes | How it was taken |
|---|---|---|
F_GETPIPE_SZ on a fresh pipe | 65,536 | the kernel’s own answer |
| Non-blocking fill, 1-byte writes | 65,536 | 65,536 writes |
| Non-blocking fill, 4,096-byte writes | 65,536 | 16 writes |
| Second fill of the same, full pipe | 0 | a full pipe accepts nothing |
| Child’s stdin pipe, 1 KiB writes | 65,536 | 64 writes to a sleeping child |
| Raised to 131,072 bytes | 131,072 | F_SETPIPE_SZ, confirmed by filling |
| Raised to 1 MiB | 1,048,576 | F_SETPIPE_SZ, confirmed by filling |
| Raised to 2,097,152 bytes | refused: Operation not permitted | 2,097,152 bytes asked, above /proc/sys/fs/pipe-max-size |
| Five repetitions at four write sizes | identical totals | minimum equals maximum at 1, 512, 4,096 and 65,536 |
Two consequences follow, and both are used later. The first is that 64 KiB is not a threshold anyone can see in application code: a child that writes 100 KiB to stdout is already blocked on its second write, and a parent that starts reading after the child has written 64 KiB is already late. The second is that the limit is per pipe and not per process, so a child with both stdout and stderr connected has 65,536 bytes of room on each side and can block on either one independently.
A detail that misleads: While the reader lives, a blocking write of more than the pipe holds reports no partial progress: it returns when all of its bytes are in, or fails. That is measured in section 5, and it is why a process blocked in a single large write shows 0 bytes written in /proc/<pid>/io even while it is holding the pipe full.
4. The read order that deadlocks
The classic bug is four lines long and looks correct: start a child with both output pipes, read one to the end, then read the other. It works for every child whose output fits in a pipe and stops working – silently, indefinitely – for every child whose output does not. The probe makes the failure exact: a child writes 16 chunks of 65,536 bytes to stdout and the same to stderr, alternating, and the parent reads stdout to EOF before looking at stderr.
from __future__ import annotations
import os
import select
import subprocess
import time
from common import CHILD, MIB, PY, child_io, status_fields
def read_with_deadline(fd: int, deadline_s: float, limit: int) -> tuple[int, float, bool]:
"""Read until EOF, or until the fd is silent for `deadline_s`.
Returns (bytes read, seconds spent, whether EOF arrived).
"""
total = 0
started = time.perf_counter()
while total < limit:
ready, _, _ = select.select([fd], [], [], deadline_s)
if not ready:
return total, time.perf_counter() - started, False
data = os.read(fd, 65536)
if not data:
return total, time.perf_counter() - started, True
total += len(data)
return total, time.perf_counter() - started, True
def sequential(order: tuple[str, str], deadline_s: float = 1.0) -> dict:
"""Read one pipe to EOF, then the other - the order that hangs."""
child = subprocess.Popen([PY, "-c", CHILD], stdout=subprocess.PIPE,
stderr=subprocess.PIPE, bufsize=0)
streams = {"stdout": child.stdout, "stderr": child.stderr}
report = {"order": list(order), "deadline_s": deadline_s}
try:
first_fd = streams[order[0]].fileno()
total, seconds, eof = read_with_deadline(first_fd, deadline_s, MIB)
report[f"{order[0]}_bytes"] = total
report[f"{order[0]}_eof"] = eof
report[f"{order[0]}_seconds_to_stall"] = round(seconds, 3)
io = child_io(child.pid)
report["child_wchar"] = io.get("wchar")
report["child_state"] = status_fields(child.pid).get("State")
report["child_rchar"] = io.get("rchar")
report["child_still_running"] = child.poll() is None
finally:
child.kill()
child.wait()
child.stdout.close()
child.stderr.close()
return report
The parent read 131,072 bytes – two pipe buffers – and then no more arrived for 1.01 seconds, which is the probe’s patience rather than the kernel’s. At that moment the child had written 196,608 bytes in total: 131,072 to stdout and one 65,536-byte chunk to stderr, after which its next write blocked. /proc/<pid>/status reported S (sleeping), which is what a process looks like when it is waiting in a pipe write – not spinning, not dead, simply unscheduled until someone reads.
Reading stderr first is the mirror image and slightly cheaper: the parent took one buffer (65,536 bytes) and the child had written 131,072 bytes when the two sides stopped talking. The asymmetry is instructive: whichever pipe is read first makes progress until the child blocks on the other, so the deadlock costs the parent exactly one buffer of reading before it becomes invisible.
| Read order | Bytes delivered | Child bytes written | Outcome |
|---|---|---|---|
| stdout to EOF, then stderr | 131,072 | 196,608 | stalled 1.01 s, child S (sleeping), no EOF |
| stderr to EOF, then stdout | 65,536 | 131,072 | stalled 1.26 s, no EOF |
communicate() | 1,048,576 + 1,048,576 | 196,608 and rising | returned in 19.6 ms, exit 0 |
subprocess.run(capture_output=True) | 1,048,576 + 1,048,576 | same | returned in 18.7 ms |
stderr=STDOUT | 2,097,152 in one stream | same | returned in 16.1 ms |
The fix is not subtle, but the reason it works is worth stating precisely: communicate() either uses a selector over both descriptors or a thread per descriptor, so neither pipe is left full while the other is read. subprocess.run is Popen plus communicate(), which is why the naive version of this bug is not in the standard library – only in the code that replaces it.
Why the order matters more than the speed: If a child’s output can be large, the pipe is the bound and not the memory: 1 MiB from each stream costs the parent 2 MiB of buffers to hold, while the child is throttled to 64 KiB at a time. Reading in a loop into a list of chunks is the same thing with worse ergonomics; the runner in section 14 caps the total so a runaway child cannot buy memory with bytes.
5. wait() with the pipes left full
The second deadlock is quieter than the first because the code contains no read at all. A child is started with stdout=PIPE, the parent calls wait(), and the child writes something larger than a pipe. The child cannot finish writing, so it cannot exit; the parent is waiting for the exit, so it never reads. Both processes are healthy, both are idle, and the pair is stuck until something outside kills one of them.
The probe starts a child that writes 524,288 bytes to stdout and exits, and the parent calls wait() without touching the pipe. After 1.5 seconds the wait had still not returned, the child was S (sleeping), and its next write was blocked. Not one byte of the 524,288 had reached the parent.
from __future__ import annotations
import subprocess
import threading
from common import PY, child_io, status_fields
def wait_undrained(deadline_s: float = 1.5, chunk: int = 524288) -> dict:
"""Child writes 512 KiB and exits; the parent calls wait() and drains nothing.
The write is split into `chunk`-sized calls, which decides what /proc/<pid>/io
shows while the child is blocked: a blocking write of more than the pipe holds
completes no syscall until it has written all of it.
"""
code = (f'import os, sys\npayload = b"o" * {chunk}\n'
f'for _ in range({524288 // chunk}):\n os.write(1, payload)\nsys.exit(0)\n')
child = subprocess.Popen([PY, "-c", code], stdout=subprocess.PIPE, bufsize=0)
returned = threading.Event()
def waiter() -> None:
child.wait()
returned.set()
thread = threading.Thread(target=waiter, daemon=True)
thread.start()
returned.wait(deadline_s)
io = child_io(child.pid)
report = {
"deadline_s": deadline_s,
"write_chunk": chunk,
"wait_returned": returned.is_set(),
"child_wchar": io.get("wchar"),
"child_state": status_fields(child.pid).get("State"),
"expected_bytes": 524288,
"pipe_capacity": 65536,
}
child.kill()
child.wait()
child.stdout.close()
return report
The same probe contains a detail that changes how a blocked child should be diagnosed. A single blocking write of 524,288 bytes into a 65,536-byte pipe shows wchar 0 in /proc/<pid>/io for as long as it is blocked, because the syscall has not returned, so the counter only advances when it does. The same 524,288 bytes written as eight 65,536-byte calls shows wchar 65,536: one full pipe, visible. So the counter is a progress meter only if the writer uses pipe-sized writes; otherwise zero written can mean a hundred kilobytes in flight.
| What the parent did | Write size in the child | wchar while blocked | wait() returned |
|---|---|---|---|
wait(), pipe never read | 524,288 bytes in one call | 0 | no, after the probe’s 1.5 s |
wait(), pipe never read | eight calls of 65,536 bytes | 65,536 | no, after the probe’s 1.75 s |
communicate() | 524,288 bytes in one call | not applicable | yes, in 13.4 ms |
In practice this failure arrives with a stack trace that points at the wait rather than at the pipe, because that is where the thread is parked. The cheapest check is the pair of counters a running kernel already keeps: /proc/<pid>/wchan will name the pipe wait, and /proc/<pid>/io will show a wchar that stopped moving. A child with a full pipe and an idle parent is one query away from diagnosis and completely invisible in a request log.
The rule: Never call wait() on a process whose pipes are unread unless the output is guaranteed to fit in a pipe – and no dependency guarantees that. If the handler needs the exit status and the output, it needs communicate(); if it needs neither, it should not have asked for pipes.
6. Zombies: a process nobody reaps
A zombie is not a bug in the child; it is a bill the parent has not paid. When a process exits, the kernel keeps its exit status and a few fields for the parent to collect with waitpid, and keeps the pid reserved while it does. If the parent never asks, the entry stays: no memory, no threads running, one line in the process table, one pid that cannot be reused.
The probe forks a child that exits with status 7 and then looks at it without waiting. /proc/<pid>/status reports Z (zombie), parent 19 – the probe itself – and 1 thread. There is no VmRSS line at all, because there is no address space left to report. It was still there after 1.5 seconds, still there after a SIGKILL, and only waitpid removed it: the raw status 1,792 decodes to exit code 7, and the /proc entry disappeared immediately afterwards.
from __future__ import annotations
import os
import pathlib
import subprocess
import time
from common import own_zombies, status_fields
def forked_zombie(hold_s: float = 1.5) -> dict:
"""Fork, let the child exit, and look at what remains."""
pid = os.fork()
if pid == 0: # child
os._exit(7)
time.sleep(0.2)
table = status_fields(pid)
report = {
"pid": pid,
"state": table.get("State"),
"ppid": table.get("PPid"),
"threads": table.get("Threads"),
"vmrss": table.get("VmRSS"),
"vmsize": table.get("VmSize"),
"alive_by_path": pathlib.Path(f"/proc/{pid}").exists(),
"held_s": hold_s,
}
time.sleep(hold_s)
report["state_after_wait_period"] = status_fields(pid).get("State")
os.kill(pid, 9) # a signal to a zombie
time.sleep(0.1)
report["state_after_sigkill"] = status_fields(pid).get("State")
reaped, status = os.waitpid(pid, 0)
time.sleep(0.1)
report["waitpid_status"] = status
report["exit_code"] = os.waitstatus_to_exitcode(status)
report["path_after_reap"] = pathlib.Path(f"/proc/{pid}").exists()
return report
def popen_batch(count: int = 20) -> dict:
"""Twenty short-lived children nobody waits for: how many zombies, and who clears them."""
keep = [subprocess.Popen(["/bin/true"]) for _ in range(count)]
time.sleep(0.3)
after_spawn = len(own_zombies())
started = time.perf_counter()
keep.append(subprocess.Popen(["/bin/true"])) # creating a Popen reaps the finished ones
time.sleep(0.2)
after_new_popen = len(own_zombies())
reap_s = round(time.perf_counter() - started, 3)
polled = [process.poll() for process in keep]
time.sleep(0.2)
after_poll = len(own_zombies())
return {
"batch": count,
"zombies_after_batch": after_spawn,
"zombies_after_new_popen": after_new_popen,
"reap_seconds": reap_s,
"returncodes_seen": sorted({code for code in polled if code is not None}),
"zombies_after_poll": after_poll,
"pids": [process.pid for process in keep],
}
Twenty short-lived children nobody waited for left 20 zombies, which is the expected one per child. What the second half of the probe shows is who cleans them up: creating another Popen left 21 – one more than before, because the new child joined the queue, and the creation reaped nothing – while calling poll() once on each object left 0. Polling is not a bookkeeping formality; it is the reaper, and it costs 7.1 microseconds per child in the loop that waited explicitly.
| Observation | Value | What it means |
|---|---|---|
| State while un-waited | Z (zombie) | the pid is held for the parent |
| Parent | 19 | the process that forked it, not an init |
| Threads | 1 | nothing is running |
VmRSS / VmSize | absent | no address space is kept |
| After SIGKILL | Z (zombie) | a signal cannot remove a zombie |
After waitpid | status 1,792, exit 7 | the status is what the wait collects |
| Twenty un-waited children | 20 zombies | one per child, exactly |
One more Popen created | 21 | creation reaped nothing |
One poll() per child | 0 | all reaped, 0.20 s of waiting |
Twenty children through run | 0 zombies | 18.9 ms for the batch |
| Explicit wait cost | 7.1 us per child | 10 children, 71.0 us in total |
The reason this matters in a service rather than in a textbook is that the failure is cumulative and delayed. Each un-reaped child costs one pid; a container with a low pid limit reaches it after thousands of calls, hours after the code that leaks them shipped, and the error that surfaces then is a BlockingIOError – Resource temporarily unavailable, errno 11, the same number a full pipe refuses with in section 3 – raised by a Popen that has nothing to do with the bug. A dashboard that only counts live processes will not see it; the signal is the count of state Z.
Orphans and init: A process that is never reaped because its parent died is a different case: the orphan is adopted by PID 1 (or by the nearest subreaper) and reaped there. In this container that did not happen, so a killed orphan stayed a zombie with parent 1 – which is why the leftover was visible at all.
7. Timeouts that kill the child and leave the tree
timeout= is a bound on one process, and a process that started a shell, a pipeline or a worker pool is a tree. The probe builds the smallest version of that tree: a child that starts a grandchild and then sleeps, with the grandchild either inheriting the parent’s pipe or pointed at /dev/null, so the two consequences can be measured separately.
from __future__ import annotations
import os
import pathlib
import subprocess
import threading
import time
from common import MARKER, PY, fields, grandchild_pids, pids_of, spawner, watch_grandchild
NAIVE = """
import subprocess, sys, time
subprocess.Popen([sys.executable, "-c", "import time; time.sleep(2) # {marker}"])
print("ready", flush=True)
time.sleep(2)
"""
def marker_trap(marker: str = MARKER) -> dict:
"""Why a command-line scan cannot name the grandchild: the spawner matches too."""
child = subprocess.Popen([PY, "-c", NAIVE.format(marker=marker)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
time.sleep(0.3)
found = pids_of(marker)
return {"marker": marker,
"matches": len(found),
"spawner_pid": child.pid,
"first_match": found[0] if found else None,
"first_match_is_spawner": bool(found) and found[0] == child.pid}
finally:
for pid in pids_of(marker):
try:
os.kill(pid, 9)
except OSError:
pass
child.wait(timeout=2)
child.stdout.close()
child.stderr.close()
def with_inherited_pipe(grace: float = 1.0) -> dict:
"""Timeout plus a grandchild holding stdout: run() waits for the pipe, not the clock."""
stop = threading.Event()
watcher: dict = {}
thread = threading.Thread(target=lambda: watcher.update(watch_grandchild(stop)), daemon=True)
thread.start()
raised = None
captured = 0
started = time.perf_counter()
try:
subprocess.run(spawner(True), capture_output=True, timeout=grace)
except subprocess.TimeoutExpired as exc:
raised = "TimeoutExpired"
captured = len(exc.stdout or b"")
elapsed = time.perf_counter() - started
stop.set()
thread.join(timeout=1)
survivor = watcher.get("pid")
report = {
"grace_s": grace,
"elapsed_s": round(elapsed, 3),
"raised": raised,
"captured_stdout_bytes": captured,
"grandchild_pid": survivor,
"grandchild_ppid": watcher.get("ppid"),
"grandchild_alive_when_parent_waited": watcher.get("last_seen") is not None,
"grandchild_seen_s": round((watcher["last_seen"] - watcher["first_seen"]), 3)
if watcher.get("last_seen") else None,
# The identification check, measured: the grandchild is the process that took
# ROLE_TAG as its comm and its parent is the spawner, while a scan for MARKER
# in this tree matches nothing - marker_trap() above shows the tree where it
# matches both, which is the bug this probe used to have.
"cmdline_matches": watcher.get("cmdline_matches"),
"marker_in_parent_cmdline": watcher.get("marker_in_parent_cmdline"),
"survivors_after_return": len(grandchild_pids()),
}
for pid in grandchild_pids():
try:
os.kill(pid, 9)
except OSError:
pass
return report
def with_devnull_grandchild(grace: float = 1.0) -> dict:
"""Timeout plus a grandchild that holds nothing: run() returns on time, the grandchild lives."""
started = time.perf_counter()
raised = None
try:
done = subprocess.run(spawner(False), capture_output=True, timeout=grace)
raw = done.stdout
except subprocess.TimeoutExpired as exc:
raised = "TimeoutExpired"
raw = exc.stdout or b""
elapsed = time.perf_counter() - started
orphan = int(raw.split()[0])
time.sleep(0.3)
alive = pathlib.Path(f"/proc/{orphan}").exists()
report = {
"grace_s": grace,
"elapsed_s": round(elapsed, 3),
"raised": raised,
"grandchild_pid": orphan,
"grandchild_state": fields(orphan).get("State"),
"grandchild_ppid": fields(orphan).get("PPid"),
"grandchild_alive": alive,
"grandchild_sid": os.getsid(orphan) if alive else None,
"grandchild_comm": pathlib.Path(f"/proc/{orphan}/comm").read_text().strip() if alive else None,
}
try:
os.kill(orphan, 9)
except OSError:
pass
time.sleep(0.25)
report["state_after_kill"] = fields(orphan).get("State")
report["proc_entry_after_kill"] = pathlib.Path(f"/proc/{orphan}").exists()
return report
Naming the grandchild took a correction, and the reason is worth a sentence because it is the kind of mistake a probe makes silently. The first version looked for a marker string in every command line, and the marker was part of the tree’s own source – which is passed to python -c, and so is the spawner’s command line. marker_trap(), printed with the probe above, rebuilds exactly that tree and records what a scan finds: 2 pids, the first of which – the one a scan hands back as the grandchild – is the spawner itself, so the old probe was timing and killing its own tree from the top. The tag now used is written by the grandchild into its own /proc/<pid>/comm when it starts, short enough that the kernel does not truncate it, and it matches exactly the one process whose parent is the spawner. The spawner’s command line holds no copy of it, which the same function reports as a measured fact – 0 command-line matches and marker_in_parent_cmdline False – rather than an assumption.
With the grandchild holding stdout, subprocess.run returned at 1.00 seconds for a 1-second timeout, raised TimeoutExpired, and had captured 2 bytes of the child’s output. It killed the direct child and left the grandchild running: the grandchild was observed alive for 0.94 seconds of the call and was still there afterwards, 1 survivor per timed-out call. On POSIX the standard library kills the child and reaps it, but does not re-communicate with the pipes, so the output that had been written but not read is simply dropped.
With the grandchild pointed at /dev/null the timeout is clean and the tree is still broken: run returned at 1.00 seconds, and the grandchild was alive with parent 1 – reparented, unreachable from the pid the caller had, still running its sleep. Killing it left a Z (zombie) entry, because nothing in this namespace reaps an orphan.
The third variant is the fix and the number that justifies it. The same tree is started in its own session, so its process group is its own; after the same 1-second grace the probe signals the group instead of the process. At that moment the group held 2 live processes. It was empty 6.0 ms later, with 0 survivors, no SIGKILL needed, and the whole call done in 1.11 seconds.
| Variant | What was signalled | Returned at | Survivors | The pipe |
|---|---|---|---|---|
| Grandchild inherits stdout | the direct child only | 1.00 s | 1 | still open; 2 bytes captured |
Grandchild on /dev/null | the direct child only | 1.00 s | 1, reparented to 1 | closed when the child died |
| Own session, group kill | the group of 2 | 1.11 s | 0 | closed with every writer, 6.0 ms to empty |
Why the survivors matter: A timeout that leaves a tree behind is worse than no timeout in one specific way: the caller believes it has cleaned up, so it retries immediately and doubles the load that caused the timeout. The surviving grandchildren are the ones that keep consuming the CPU or the file handle that made the first call slow.
8. Process groups, and the six milliseconds it takes
A process group is the unit a terminal uses for Ctrl-C and the unit a supervisor should use for a timeout, and by default a child joins the group of the process that started it. That default is what makes os.killpg(os.getpgid(child.pid), sig) dangerous: it signals the caller as well. The probe measures the difference before using it, and the module in section 14 closes the trap in the API: its two group functions refuse a group id of 0 or 1 rather than passing it to killpg.
from __future__ import annotations
import os
import pathlib
import subprocess
import time
from common import PY, fields, members, spawner, wait_until_empty
IGNORING = ("import signal, time\n"
"signal.signal(signal.SIGTERM, lambda *a: None)\n"
"print('armed', flush=True)\n"
"time.sleep(60)")
IGNORING_TREE = ("import signal, subprocess, sys, time\n"
"signal.signal(signal.SIGTERM, lambda *a: None)\n"
f"grandchild = subprocess.Popen([sys.executable, '-c', {IGNORING!r}],\n"
" stdout=subprocess.PIPE)\n"
"grandchild.stdout.readline()\n"
"print('ready', flush=True)\n"
"time.sleep(60)\n")
def group_kill(grace: float = 1.0, term_wait: float = 0.5) -> dict:
"""The same tree, started in its own session, killed by process group."""
child = subprocess.Popen(spawner(True), stdout=subprocess.PIPE,
stderr=subprocess.PIPE, start_new_session=True, bufsize=0)
pgid = os.getpgid(child.pid)
started = time.perf_counter()
members_at_signal = 0
leader_names_a_process = pathlib.Path(f"/proc/{pgid}").exists()
try:
grace_deadline = started + grace
while time.perf_counter() < grace_deadline:
time.sleep(0.02)
members_at_signal = len(members(pgid))
os.killpg(pgid, 15)
escalated = False
gone = wait_until_empty(pgid, term_wait)
if members(pgid):
escalated = True
os.killpg(pgid, 9)
wait_until_empty(pgid, 2.0)
child.wait(timeout=2)
time.sleep(0.1)
report = {
"grace_s": grace,
"pgid": pgid,
"child_pid": child.pid,
"pgid_is_child_pid": pgid == child.pid,
"pgid_names_a_process": leader_names_a_process,
"own_pgid": os.getpgid(0),
"own_session_shared": pgid == os.getpgid(0),
"elapsed_s": round(time.perf_counter() - started, 3),
"members_at_signal": members_at_signal,
"survivors": len(members(pgid)),
"signal_to_empty_s": round(gone, 3),
"escalated_to_sigkill": escalated,
"child_returncode": child.returncode,
}
finally:
for pid in members(pgid):
try:
os.kill(pid, 9)
except OSError:
pass
if child.poll() is None:
child.kill()
child.wait()
child.stdout.close()
child.stderr.close()
return report
def group_escalation(term_grace: float = 0.5, kill_grace: float = 2.0) -> dict:
"""A group where every process ignores SIGTERM: the grace expires, then SIGKILL."""
child = subprocess.Popen([PY, "-c", IGNORING_TREE], stdout=subprocess.PIPE,
start_new_session=True, bufsize=0)
pgid = os.getpgid(child.pid)
try:
child.stdout.readline()
members_before = len(members(pgid))
started = time.perf_counter()
os.killpg(pgid, 15)
gone_after_term = wait_until_empty(pgid, term_grace)
survivors_after_term = len(members(pgid))
escalated_at = time.perf_counter() - started
os.killpg(pgid, 9)
gone_after_kill = wait_until_empty(pgid, kill_grace)
report = {
"term_grace_s": term_grace,
"members_at_signal": members_before,
"survivors_after_sigterm": survivors_after_term,
"term_to_empty_s": round(gone_after_term, 3),
"escalation_after_s": round(escalated_at, 3),
"signal_to_empty_after_sigkill_s": round(gone_after_kill, 3),
"child_returncode": child.wait(timeout=kill_grace),
"survivors": len(members(pgid)),
}
finally:
for pid in members(pgid):
try:
os.kill(pid, 9)
except OSError:
pass
if child.poll() is None:
child.kill()
child.wait()
child.stdout.close()
return report
def default_group() -> dict:
"""A child started without a new session shares the test runner's process group.
Both ids read 0 in this container, and that 0 is not the POSIX convention's "the
caller's own group": the session and group leaders live outside this pid namespace,
so the id has no name inside it. The report measures what separates the two
readings - the child is in this namespace, and the id it reports names no process -
so the article can say which zero is being quoted.
"""
child = subprocess.Popen(spawner(False), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
pgid = os.getpgid(child.pid)
return {"child_pid": child.pid,
"child_pgid": pgid,
"child_ppid": fields(child.pid).get("PPid"),
"runner_pid": os.getpid(),
"pgid_names_a_process": pathlib.Path(f"/proc/{pgid}").exists(),
"own_pgid": os.getpgid(0),
"same_group": pgid == os.getpgid(0)}
finally:
child.kill()
child.wait()
child.stdout.close()
child.stderr.close()
Started without a new session, the child’s process group id was 0, exactly the caller’s 0 – the same group. A group kill at that point would have delivered SIGTERM to the probe, and the probe would have exited without writing its results – a failure that looks like a crash and is actually a self-inflicted signal. Started with start_new_session=True the group id was 11, its own, with 2 members.
Both of the first pair read 0, and that number is worth reading carefully because the same digit appears on both sides of the comparison: it is this container’s notation for a group whose leader it cannot see, not the POSIX shorthand that means “the caller’s own group”, though a signal sent to it lands in the same place. The session and group leaders here live outside the container’s pid namespace, so the id has no name inside it and getpgid reports zero for every process that did not start a session of its own. default_group(), printed with the probe above, records what separates the two readings rather than asking the reader to take the zero on trust: the child’s own pid was 15, its parent was the probe (3), so both processes are in this namespace – while the id the child reported names no process there at all (/proc/0 does not exist). A child that calls setsid, as the group-kill child does, gets an id that does name a process – a new session leader’s group id is its own pid, and there both were 11.
Signalling that group and watching it empty is the cheap part: 6.0 ms from killpg(SIGTERM) to no live member, with the direct child’s return code -15 – the negative number a shell reports as the signal that ended it. The empty-group wait polls every few milliseconds and excludes zombies, because a killed child stays listed in its group until its parent reaps it; counting it would report a successful kill as a failure. That distinction is the whole reason the members helper printed in section 1 filters on state.
| Signal target | Group id | Members at signal | Empty after | Survivors |
|---|---|---|---|---|
child only (kill) | n/a | 2 | never | 1 in the inherited-pipe case |
group (killpg), own session | 11 | 2 | 6.0 ms | 0 |
| group, caller’s session | 0 | the caller and its children | n/a | the caller dies with it |
Two rules follow. Start every long-running child with start_new_session=True so that its group is separable, and store the group id next to the pid, because the pid may be reaped and reused while the group still exists. Then signal the group, wait a bounded grace period, and escalate to SIGKILL: a child that installed a SIGTERM handler to flush a buffer is doing the right thing and deserves the grace period, while a child stuck in an uninterruptible call needs the second signal.
Escalation is not optional: A SIGTERM that a child ignores is not a failure of the signal; it is the reason the escalation exists. group_escalation(), printed with the probe above, starts a two-process group in which both processes install a SIGTERM handler and confirm they are armed before the probe proceeds, signals the group, and waits the grace period: 2 of 2 processes were still alive 0.504 s later, so what expired was the grace rather than the group emptying. killpg(SIGKILL) emptied it 6.0 ms after that, with 0 survivors and the child’s return code -9 – the negative number a shell reports as the signal that ended it. Every kill_group that reports escalated has met one of these, and the grace period is what separates a child that flushes its buffer from one that never will.
9. What a full pipe costs the writer
Everyone worries about the reader; the writer is where the latency lands. A blocking write into a pipe returns when all of its bytes have been copied into the buffer, so its duration is the reader’s pace whenever the pipe is full. The probe measures that directly with a single 204,800-byte write into a 64 KiB pipe whose reader consumes 8 KiB every 5 ms.
The write returned all 204,800 bytes – while the reader is alive, a blocking pipe write returns when every byte is in – and it returned them 81.9 ms after it was called. At that instant the reader had taken 139,264 bytes and 65,536 bytes were still sitting in the pipe: 139,264 read plus 65,536 buffered is exactly the 204,800 bytes requested. That sum is the arithmetic of the whole section: a blocking write can return while the reader has seen only part of it, because the kernel took the rest into its buffer. The reader went on to consume the remaining bytes (204,800 in total), which is why a probe that measures the reader after joining its thread sees all of it and explains nothing.
from __future__ import annotations
import array
import fcntl
import os
import statistics
import subprocess
import termios
import threading
import time
from common import PYTHON
BODY = 32 << 20
SINK = ("import sys\nview = memoryview(bytearray(1 << 20))\n"
"while True:\n data = sys.stdin.buffer.readinto(view)\n"
" if not data:\n break\n")
def transfer(chunk: int, pipesize: int | None = None) -> dict:
"""Write BODY into a child's stdin in `chunk`-sized calls."""
kwargs = {"stdin": subprocess.PIPE, "bufsize": 0}
if pipesize is not None:
kwargs["pipesize"] = pipesize
child = subprocess.Popen([PYTHON, "-c", SINK], **kwargs)
payload = b"x" * chunk
writes: list[float] = []
sent = 0
started = time.perf_counter()
try:
while sent < BODY:
write_started = time.perf_counter()
child.stdin.write(payload)
writes.append((time.perf_counter() - write_started) * 1000)
sent += chunk
child.stdin.close()
child.wait(timeout=60)
finally:
if child.poll() is None:
child.kill()
child.wait()
try:
child.stdin.close()
except OSError:
pass
elapsed = time.perf_counter() - started
return {
"chunk": chunk,
"pipesize": pipesize or 65536,
"writes": len(writes),
"bytes": sent,
"elapsed_ms": round(elapsed * 1000, 3),
"mib_per_s": round(sent / (1 << 20) / elapsed, 1),
"median_write_ms": round(statistics.median(writes), 3),
"max_write_ms": round(max(writes), 3),
}
def raw_write_block() -> dict:
"""One write of 200 KiB into a 64 KiB pipe, with a slow reader: where does the call sit?
The question the article answers is arithmetic, so the probe snapshots both
sides the moment the write returns: bytes the reader has taken, and bytes still
in the pipe (FIONREAD). They must add up to the request - that sum is why a
blocking write can return at all.
"""
read_fd, write_fd = os.pipe()
received = {"bytes": 0}
lock = threading.Lock()
def reader() -> None:
while True:
try:
data = os.read(read_fd, 8192)
except OSError:
return
if not data:
return
with lock:
received["bytes"] += len(data)
time.sleep(0.005)
thread = threading.Thread(target=reader, daemon=True)
thread.start()
payload = b"y" * (200 * 1024)
started = time.perf_counter()
written = os.write(write_fd, payload)
blocked_ms = (time.perf_counter() - started) * 1000
with lock:
reader_at_return = received["bytes"]
in_pipe = array.array("i", [0])
fcntl.ioctl(read_fd, termios.FIONREAD, in_pipe)
pipe_at_return = in_pipe[0]
thread.join(timeout=2)
os.close(write_fd)
os.close(read_fd)
return {"requested_bytes": len(payload), "returned_bytes": written,
"blocked_ms": round(blocked_ms, 3),
"reader_bytes_at_return": reader_at_return,
"pipe_bytes_at_return": pipe_at_return,
"accounted_bytes": reader_at_return + pipe_at_return,
"reader_bytes_total": received["bytes"],
"reader_chunk": 8192, "reader_delay_ms": 5}
Against a fast reader the same transfer looks entirely different. Thirty-two MiB written as 1 KiB chunks moved 677.4 MiB/s over 32,768 writes; as 64 KiB chunks 1,242.3 MiB/s over 512 writes; as 1 MiB chunks 788.7 MiB/s over 32 writes. Five runs each tell the same story: the 1 KiB case is the slow one (533.1 to 722.2 MiB/s), 64 KiB chunks were fastest (956.3 to 1,455.3), and 1 MiB chunks were slower than 64 KiB in every run (706.5 to 835.9). The surprise is the direction: bigger writes were not better. One reading of that is that a megabyte at a time leaves the reader fewer chances to drain the pipe between writes; the probe did not measure the reader’s own scheduling, so that is an interpretation of these five runs rather than a cause the probe established.
| Write size | Writes per 32 MiB | Throughput (median) | Five runs (MiB/s) | Slowest write |
|---|---|---|---|---|
| 1 KiB | 32,768 | 677.4 MiB/s | 533.1 – 722.2 | 17.3 ms |
| 64 KiB | 512 | 1,242.3 MiB/s | 956.3 – 1,455.3 | 11.1 ms |
| 1 MiB | 32 | 788.7 MiB/s | 706.5 – 835.9 | 11.3 ms |
07_write_cost.py (raw_write) measures what happens when it does not.Every row has a slowest write of about ten milliseconds even though the median write is microseconds. That is consistent with the pipe being full: the writer runs ahead of the reader until the buffer is occupied, then takes one long hit, then runs ahead again. A tail-latency graph of a service that writes to a subprocess shows exactly this shape, and it is not the child being slow – it is the parent waiting for a buffer slot.
The other end of the same mechanism is the reader that left. A child that has already exited turns the next write into BrokenPipeError: the probe sent 0 bytes and got the exception on attempt 1. Python ignores SIGPIPE by default, which is why this arrives as an exception that can be caught per stream instead of as a signal that ends the process – a useful default that is worth knowing before writing a handler that treats every write error as fatal.
10. A bigger pipe
If the writer’s cost is a full buffer, the obvious lever is a bigger buffer. Linux lets an unprivileged process raise a pipe up to 1,048,576 bytes, and section 3 confirmed that the kernel grants 131,072 and 1,048,576 when asked and refuses anything above the maximum with Operation not permitted. The probe then repeats the 64 KiB transfer with pipes of three sizes, five runs each.
With a 65,536-byte pipe the same 32 MiB moved at 1,294.1 MiB/s; at 262,144 bytes, 1,436.9 MiB/s; at 1,048,576 bytes, 1,514.2 MiB/s. Not every gap survives the spread: the default pipe ran between 1,154.8 and 1,449.1 MiB/s and the 262,144-byte pipe between 1,282.5 and 1,550.7, so those two overlap. The one ordering every run supports is the 1 MiB pipe against the default: 1,497.1 to 1,551.0 against 1,154.8 to 1,449.1. Raising the capacity removes some of the writer’s stalls; the rest is the reader’s own rate.
| Pipe capacity (bytes) | Throughput (median) | Five runs (MiB/s) |
|---|---|---|
| 65,536 (default) | 1,294.1 MiB/s | 1,154.8 – 1,449.1 |
| 262,144 | 1,436.9 MiB/s | 1,282.5 – 1,550.7 |
| 1,048,576 | 1,514.2 MiB/s | 1,497.1 – 1,551.0 |
The caveats are the interesting part. The capacity is per pipe, so a child with stdin and stdout doubled costs twice, and the kernel memory is not visible to the process’s own accounting. It also does not remove the deadlock: a child that writes 2 MiB still blocks once the buffer is full, it just blocks later. The pipe size is a tail-latency lever, not a correctness one.
When not to raise it: Raise the pipe only for a child whose output you actually stream and whose writer you have measured. For a child that produces a short result and exits, the default is already larger than the result, and a bigger buffer simply delays the first read.
11. Which reader, and which read size
Once the decision is to drain, the next question is how. The probe reads the same 32 MiB of a child’s stdout three ways: communicate(), one read() on the BufferedReader, and a loop of os.read with 64 KiB buffers.
from __future__ import annotations
import os
import subprocess
import time
from common import PYTHON
SOURCE = ('import os, sys\nbody = b"o" * (1 << 20)\n'
"for _ in range({mib}):\n os.write(1, body)\n")
def drain(method: str) -> dict:
"""Read 32 MiB from a child's stdout three ways."""
child = subprocess.Popen([PYTHON, "-c", SOURCE.format(mib=32)],
stdout=subprocess.PIPE, bufsize=0)
total = 0
reads = 0
started = time.perf_counter()
try:
if method == "communicate":
out, _ = child.communicate(timeout=60)
total = len(out)
reads = 1
elif method == "read_all":
out = child.stdout.read()
total = len(out)
reads = 1
else:
while True:
data = os.read(child.stdout.fileno(), 65536)
if not data:
break
total += len(data)
reads += 1
child.wait(timeout=60)
finally:
if child.poll() is None:
child.kill()
child.wait()
child.stdout.close()
elapsed = time.perf_counter() - started
return {"method": method, "bytes": total, "reads": reads,
"elapsed_ms": round(elapsed * 1000, 3),
"mib_per_s": round(total / (1 << 20) / elapsed, 1)}
os.read in 64 KiB buffers was fastest in every run, 853.9 to 921.0 MiB/s against 585.3 to 697.8 for a single read(). The two are not ranked here: the medians differ by about a tenth (574.5 against 649.8 MiB/s), but read() itself ran from 585.3 to 697.8 across five runs – a spread wider than that gap – and communicate() threw one outlier at 111.3 MiB/s against four runs between 434.7 and 577.5. A difference inside the run-to-run spread is reported as flat, so it is.
| Method | Reads for 32 MiB | Throughput (median) | Five runs (MiB/s) | What it cannot do |
|---|---|---|---|---|
communicate() | one call | 574.5 MiB/s | 434.7 – 577.5 (one at 111.3) | return before both pipes reach EOF |
stdout.read() | one call | 649.8 MiB/s | 585.3 – 697.8 | drain a second pipe at the same time |
os.read, 64 KiB | 512 reads | 916.7 MiB/s | 853.9 – 921.0 | be stopped while blocked, unless it waits in select first |
communicate() and read() sit inside each other’s spread; the explicit 64 KiB loop is faster than both.For a service the ranking is less important than the last column. communicate() is the only one that handles both pipes and a timeout in one call, which is why the correct default is the slower of the three. A custom runner earns its complexity only when it has to do something communicate() will not: stop reading at a byte limit, keep reading after the child exits, or report the pipe as abandoned instead of waiting for it.
The one design constraint that matters: A reader that blocks in os.read cannot be cancelled. That is why the drain in this article waits in select with a short poll first: a thread parked in a syscall ignores an event, while a thread that wakes every 50 ms can be told to stop and leave the descriptor to be closed by its owner.
12. Who keeps the pipe open
The timeout in section 7 left a survivor holding a pipe, and that is the mechanism behind most “the call returned but the reader is still waiting” reports. The probe follows it exactly: it opens a pipe, starts a child that duplicates the write end onto fd 1, has that child start a grandchild, then exits. It then identifies the pipe by its inode and looks for every descriptor on the host that points at it.
from __future__ import annotations
import os
import pathlib
import select
import subprocess
import time
from common import PY, inode_of
def holders(inode: str) -> list[tuple[int, int]]:
"""Every (pid, fd) whose target is this pipe inode, across the visible /proc."""
found = []
for entry in pathlib.Path("/proc").iterdir():
if not entry.name.isdigit():
continue
pid = int(entry.name)
try:
names = os.listdir(f"/proc/{pid}/fd")
except (FileNotFoundError, PermissionError):
continue
for name in names:
try:
target = os.readlink(f"/proc/{pid}/fd/{name}")
except OSError:
continue
if target.endswith(f"[{inode}]"):
found.append((pid, int(name)))
return sorted(found)
def grandchild_holds_pipe() -> dict:
"""The child exits; its child keeps the pipe, so the reader never sees EOF."""
read_fd, write_fd = os.pipe()
inode = inode_of(write_fd)
code = (f'import os, subprocess, sys, time\n'
f'os.dup2({write_fd}, 1)\n'
f'child = subprocess.Popen(["/bin/sleep", "2"], stdout=None)\n'
f'print(child.pid, file=sys.stderr, flush=True)\n'
f'time.sleep(0.1)\n')
proc = subprocess.Popen([PY, "-c", code], stderr=subprocess.PIPE, pass_fds=(write_fd,))
os.close(write_fd)
first = proc.stderr.readline().decode().strip()
grandchild = int(first)
proc.wait(timeout=5)
holders_now = holders(inode)
pid_holder_count = len({pid for pid, _ in holders_now})
eof = False
deadline = time.perf_counter() + 1.5
while time.perf_counter() < deadline:
ready, _, _ = select.select([read_fd], [], [], 0.1)
if ready:
data = os.read(read_fd, 1024)
if not data:
eof = True
break
report = {
"grandchild_pid": grandchild,
"grandchild_state": pathlib.Path(f"/proc/{grandchild}/status").read_text().splitlines()[2].strip()
if pathlib.Path(f"/proc/{grandchild}/status").exists() else None,
"grandchild_holds_inode": any(pid == grandchild for pid, _ in holders_now),
"holder_processes": pid_holder_count,
"holder_fds": len(holders_now),
"eof_within_s": 1.5,
"eof_seen": eof,
"read_end_pid": os.getpid(),
}
os.close(read_fd)
try:
os.kill(grandchild, 9)
except OSError:
pass
proc.stderr.close()
return report
After the child exited, 2 processes still held the pipe – the probe on the read end and the grandchild on the write end – across 2 descriptors, and a reader waiting on the probe’s end saw no EOF within 1.5 seconds. Nothing was wrong with the parent’s descriptor arithmetic: the write end simply had a second owner that nobody knew about.
The same probe answers the usual objection, which is that close_fds=True makes this impossible. It is true that a child does not inherit arbitrary descriptors by accident: with 50 extra descriptors open in the parent, the child saw 4 – standard input, output, error and the exec-status pipe – and the same 4 with close_fds=False, because those descriptors are created close-on-exec. It is also true that the three standard descriptors are always inherited, which is exactly how a pipe gets a second owner. A descriptor made inheritable on purpose is visible in the child, and one passed with pass_fds is visible as well, while the same descriptor without the argument is not.
| Situation | Child descriptors | Pipe still open after the child exits |
|---|---|---|
50 descriptors open, close_fds=True | 4 | no |
50 descriptors open, close_fds=False | 4 | no – close-on-exec keeps them |
descriptor 4 passed with pass_fds | one extra, fd 4 | yes, if it is a pipe |
| grandchild inheriting fd 1 from a child | 3 in the grandchild | yes: 2 holders, 1.5 s without EOF |
That is why the fix in section 7 is a group kill and not a bigger timeout: the only reliable way to close a pipe whose owner you cannot see is to end every process that could hold it. When a grandchild escapes the group – its own start_new_session, a daemonised worker, a re-exec – no group signal reaches it, and the runner’s only remaining option is to stop waiting deliberately and report the pipe as abandoned rather than hang. The module in section 14 does exactly that and calls the outcome escaped.
13. asyncio: three descriptors per child
The asyncio version of a subprocess has the same pipes and one extra descriptor per child: a pidfd, which is how the event loop learns that a process exited without a thread per child. The probe spawns one hundred children with both output pipes, keeps them alive, and counts descriptors from /proc/self/fd rather than from the transport’s own bookkeeping.
from __future__ import annotations
import asyncio
import gc
import os
import threading
import time
from common import zombies
N = 100
def fds() -> int:
return len(os.listdir("/proc/self/fd"))
def pipe_fds() -> int:
count = 0
for name in os.listdir("/proc/self/fd"):
try:
if os.readlink(f"/proc/self/fd/{name}").startswith("pipe:"):
count += 1
except OSError:
continue
return count
def snapshot() -> dict:
return {"fds": fds(), "pipes": pipe_fds(), "zombies": len(zombies()),
"threads": threading.active_count()}
async def spawn_storm(command: list[str]) -> dict:
"""N children, two pipes each, nobody waits: the descriptors are held while they live."""
before = snapshot()
started = time.perf_counter()
procs = [await asyncio.create_subprocess_exec(
*command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
for _ in range(N)]
spawn_ms = (time.perf_counter() - started) * 1000
await asyncio.sleep(0.5)
alive = snapshot()
for proc in procs:
if proc.returncode is None:
try:
proc.kill()
except ProcessLookupError:
pass
await asyncio.sleep(0.3)
killed = snapshot()
await asyncio.gather(*(proc.wait() for proc in procs))
await asyncio.sleep(0.2)
gc.collect()
awaited = snapshot()
return {"n": N, "before": before, "spawn_ms": round(spawn_ms, 3), "while_alive": alive,
"after_kill": killed, "after_wait": awaited,
"returncodes": sorted({proc.returncode for proc in procs})}
async def clean_run() -> dict:
before = snapshot()
started = time.perf_counter()
for _ in range(N):
proc = await asyncio.create_subprocess_exec(
"/bin/true", stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
await proc.communicate()
elapsed_ms = (time.perf_counter() - started) * 1000
await asyncio.sleep(0.1)
return {"n": N, "before": before, "after": snapshot(), "elapsed_ms": round(elapsed_ms, 3),
"us_per_child": round(elapsed_ms * 1000 / N, 1)}
Before the storm the process had 7 descriptors; with 100 children alive it had 307, of which 202 were pipes. The difference is three per child: two pipe ends and one pidfd. After the children were killed the count returned to 7 without anything being closed by hand, which is the useful half of the answer: descriptors follow the child’s lifetime, so a leak here is not a leak in the usual sense – it is a child that never ends. A service that spawns a process per request and loses track of it holds three descriptors per request until the process exits, and if the process is waiting on a pipe nobody reads, that is forever.
A hundred children through communicate() cost 1.0 ms each (102.9 ms for the hundred) and left no descriptor behind; the same hundred spawned and abandoned cost 64.7 ms to start, while a hundred that exit immediately cost 56.5 ms and cleaned themselves up before the snapshot could see them.
| Census point | Descriptors | Pipe descriptors | Zombies |
|---|---|---|---|
| before | 7 | 2 | 0 |
| 100 children alive | 307 | 202 | 0 |
| after killing them | 7 | 2 | 0 |
| after waiting for them | 7 | 2 | 0 |
100 children through communicate() | 7 | 2 | 0 |
The deadlock, however, is identical. A coroutine that reads the child’s stdout to EOF before touching stderr stalls in the same place, and the number of bytes it manages to read is larger than in the threaded case because the stream has its own buffer on top of the pipe.
from __future__ import annotations
import asyncio
import time
from common import CHILD, PY, status_fields
async def read_to_stall(limit_bytes: int = 1 << 20) -> dict:
proc = await asyncio.create_subprocess_exec(
PY, "-c", CHILD, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
total = 0
started = time.perf_counter()
try:
while total < limit_bytes:
try:
data = await asyncio.wait_for(proc.stdout.read(65536), timeout=1.0)
except asyncio.TimeoutError:
break
if not data:
break
total += len(data)
return {"stdout_bytes": total, "expected_bytes": limit_bytes,
"stalled_s": round(time.perf_counter() - started, 3),
"child_state": status_fields(proc.pid).get("State"),
"reader_limit": 65536}
finally:
if proc.returncode is None:
proc.kill()
try:
await asyncio.wait_for(proc.wait(), 2.0)
except asyncio.TimeoutError:
pass
The coroutine read 327,680 bytes – 5 pipe buffers – in three identical trials, then waited 1.01 seconds for more before giving up on it. communicate() on the same child returned both 1 MiB streams in 16.3 ms. The three abandoned transports for the stalled children each raised RuntimeError: Event loop is closed from their destructor when the loop closed, 3 errors that a service would see as noise in its log and never connect to the handler that walked away.
| Measurement | Result | Note |
|---|---|---|
| Bytes read before the stall | 327,680 | 5 buffers of 64 KiB, identical across 3 trials |
| Time to the stall | 1.01 s | the probe’s patience, not a kernel limit |
communicate() for the same child | 16.3 ms | both streams, 1 MiB each |
| Abandoned transports at loop close | 3 | each reported RuntimeError: Event loop is closed |
| Child state at the stall | S (sleeping) | blocked in write, exactly as in the threaded case |
The log line that gives it away: In asyncio the failure has one extra exit: a transport that is garbage collected while its pipes are open tries to schedule a callback on a closed loop. That is the RuntimeError: Event loop is closed line in the log, and its presence means a child was abandoned – there is no benign reason for it once the loop has stopped.
If this runbook saved you an afternoon: the AI Prompt Pack for engineers and the Zero-Crash Python newsletter – free, one production failure per issue.
14. The module: procguard, its first bugs, and its sixty tests
The module below is the article compiled into a library. It is deliberately small: one file for the pipe, one for process groups, one for the synchronous runner, one for the asyncio runner, and an __init__ that names them. Every line of the package in this section is the file, not an extract, so the five modules printed here are what the tests ran against and what the measurements in Table 15 executed.
procguard/pipe.py – capacity and a drain that can be stopped
Drain is a thread rather than a generator so that it can read while the parent waits on something else, and it waits in select with a 50 ms poll so that stop() works when the pipe has a writer the runner cannot kill. The byte limit is applied under the same lock as appends, which is why truncated is exact rather than approximate: past the limit the thread keeps reading and discards, so the child is never blocked by a reader that stopped.
"""Pipe capacity, and a reader that cannot be trapped by a child nobody waits for."""
from __future__ import annotations
import fcntl
import os
import select
import threading
F_GETPIPE_SZ = getattr(fcntl, "F_GETPIPE_SZ", 1032)
F_SETPIPE_SZ = getattr(fcntl, "F_SETPIPE_SZ", 1031)
DEFAULT_CHUNK = 65536
def pipe_capacity(fd: int) -> int:
"""The number of bytes the kernel will hold in this pipe before a write blocks."""
return fcntl.fcntl(fd, F_GETPIPE_SZ)
def set_pipe_capacity(fd: int, size: int) -> int:
"""Ask for a larger pipe and return the size the kernel actually granted.
The kernel rounds up to a page, refuses anything above /proc/sys/fs/pipe-max-size
with EPERM, and the returned value is the only one worth reporting.
"""
return fcntl.fcntl(fd, F_SETPIPE_SZ, size)
def fill_until_eagain(fd: int, chunk: int = DEFAULT_CHUNK) -> int:
"""Write into a non-blocking pipe until it refuses, returning the bytes accepted."""
os.set_blocking(fd, False)
payload = b"x" * chunk
total = 0
while True:
try:
total += os.write(fd, payload)
except BlockingIOError:
return total
class Drain(threading.Thread):
"""Read one descriptor to EOF on its own thread, and stop when told to.
A drain that blocks in ``os.read`` cannot be stopped, which is exactly the state
a pipe held open by an escaped grandchild puts a runner in. This one waits in
``select`` with a short timeout instead, so ``stop()`` and ``join(deadline)``
always return and the caller can decide what a missing EOF means.
"""
def __init__(self, fd: int, *, chunk: int = DEFAULT_CHUNK, limit: int | None = None,
poll_s: float = 0.05) -> None:
super().__init__(daemon=True)
self.fd = fd
self.chunk = chunk
self.limit = limit
self.poll_s = poll_s
self.buffer = bytearray()
self.truncated = False
self.error: BaseException | None = None
self.finished = False
self._stop_event = threading.Event()
self._lock = threading.Lock()
def run(self) -> None:
try:
while not self._stop_event.is_set():
ready, _, _ = select.select([self.fd], [], [], self.poll_s)
if not ready:
continue
data = os.read(self.fd, self.chunk)
if not data:
self.finished = True
return
with self._lock:
room = None if self.limit is None else self.limit - len(self.buffer)
if room is not None and room <= 0:
self.truncated = True
continue
# A chunk that fits is appended whole: slicing it first would copy
# every captured byte twice for nothing.
self.buffer += data if room is None or len(data) <= room else data[:room]
if room is not None and len(data) > room:
self.truncated = True
except (OSError, ValueError) as exc:
self.error = exc
finally:
self.finished = True
def stop(self) -> None:
"""Ask the thread to return at its next poll, without waiting for EOF."""
self._stop_event.set()
def bytes(self) -> bytes:
with self._lock:
return bytes(self.buffer)
def size(self) -> int:
with self._lock:
return len(self.buffer)
procguard/group.py – what a signal reaches
group_members reads /proc instead of calling getpgid on a pid it may already have lost, and it excludes zombies so that a successful kill is not reported as a survivor. kill_group returns its report rather than raising, because it is called from exception handlers where a second exception would hide the first, and terminate_tree refuses to call killpg when the process shares the caller’s group – the trap in section 8.
One input does raise, before anything is read or signalled: both public group functions refuse a group id of 0 or 1 with ValueError. That is the same trap from the other side. Section 8 measured a child reporting group id 0 because its leader sits outside the namespace, and a caller that stored that id and passed it back would be asking for killpg(0, ...) – a signal to its own group, and to every child it has. group_members(0) is no safer: the scan would return the processes of the invisible group as if they were one group. Six tests in the group module press that button, passing 0, 1 and a negative id to each function and asserting the refusal rather than a signal.
"""Process groups: what a signal reaches, and what it leaves behind."""
from __future__ import annotations
import os
import pathlib
import signal
import time
POLL_S = 0.005
def proc_state(pid: int) -> str:
"""One letter from /proc/<pid>/status: R, S, D, Z, T or X. Empty if the pid is gone."""
try:
text = pathlib.Path(f"/proc/{pid}/status").read_text()
except (FileNotFoundError, ProcessLookupError):
return ""
for line in text.splitlines():
if line.startswith("State:"):
return line.split()[1]
return ""
def group_members(pgid: int) -> list[int]:
"""Live pids in a process group, read from /proc/<pid>/stat.
A group id of 0 or 1 is refused rather than scanned. ``getpgid`` reports 0 for
a group whose leader sits outside this pid namespace, and that 0 is not the
POSIX shorthand for "the caller's group": every process of the invisible group
carries 0 in ``/proc/<pid>/stat`` too, so a scan for it returns this process
and its children instead of one group, and a signal sent to it lands on them.
Zombies are excluded: a killed child stays in its group until it is reaped, and
counting it would report a kill that worked as one that did not.
"""
if pgid <= 1:
raise ValueError(f"refusing process group id {pgid}: no group of that id can be "
"named safely, so nothing was counted")
members = []
for entry in pathlib.Path("/proc").iterdir():
if not entry.name.isdigit():
continue
try:
text = pathlib.Path(f"/proc/{entry.name}/stat").read_text()
except (FileNotFoundError, ProcessLookupError):
continue
tail = text[text.rfind(")") + 2:].split()
try:
if int(tail[2]) != pgid or tail[0] == "Z":
continue
except (IndexError, ValueError):
continue
members.append(int(entry.name))
return sorted(members)
def kill_group(pgid: int, *, grace_s: float = 0.5, poll_s: float = POLL_S) -> dict:
"""SIGTERM the group, wait, then SIGKILL whatever is left.
Returns what happened rather than raising: a caller in an exception handler
needs to know whether the group emptied, not to be interrupted by a second error.
A group id of 0 or 1 is the one input that raises instead, before anything is
signalled. ``os.killpg(0, sig)`` means "the caller's own group", and 0 is also
what ``getpgid`` reports for a group whose leader is outside this pid namespace,
so a caller that stored that id and passed it back would lose its own process
and every child it has - the failure section 8 measured, closed here instead of
in each caller.
"""
if pgid <= 1:
raise ValueError(f"refusing process group id {pgid}: killpg would signal the "
"caller's own group, so no signal was sent")
report = {"pgid": pgid, "members_before": len(group_members(pgid)),
"sent": [], "survivors": 0, "empty_s": None, "escalated": False}
started = time.perf_counter()
try:
os.killpg(pgid, signal.SIGTERM)
report["sent"].append("SIGTERM")
except ProcessLookupError:
report["empty_s"] = 0.0
return report
empty_s = wait_empty(pgid, grace_s, poll_s)
if empty_s is not None:
report["empty_s"] = round(empty_s, 3)
return report
report["escalated"] = True
try:
os.killpg(pgid, signal.SIGKILL)
report["sent"].append("SIGKILL")
except ProcessLookupError:
report["empty_s"] = round(time.perf_counter() - started, 3)
return report
empty_s = wait_empty(pgid, grace_s, poll_s)
report["empty_s"] = None if empty_s is None else round(empty_s, 3)
report["survivors"] = len(group_members(pgid))
return report
def wait_empty(pgid: int, timeout_s: float, poll_s: float = POLL_S) -> float | None:
"""Seconds until the group holds no live process, or None if it still does.
Refuses a group id of 0 or 1 through ``group_members``, so a caller cannot poll
the invisible group without meeting the same guard.
"""
started = time.perf_counter()
while time.perf_counter() - started < timeout_s:
if not group_members(pgid):
return time.perf_counter() - started
time.sleep(poll_s)
return None
def terminate_tree(process, *, grace_s: float = 0.5) -> dict:
"""Kill everything a Popen started, if it was started in its own session.
Without ``start_new_session=True`` the child shares this process's group, and
killpg would signal the caller too; that case is reported, not acted on.
"""
pgid = os.getpgid(process.pid)
if pgid == os.getpgid(0):
process.kill()
return {"pgid": pgid, "shared_with_caller": True, "sent": ["SIGKILL"],
"survivors": 0, "escalated": False, "empty_s": None}
report = kill_group(pgid, grace_s=grace_s)
report["shared_with_caller"] = False
return report
procguard/run.py – the synchronous runner
run_captured starts the child in its own session, drains both pipes from the first millisecond, and polls the clock rather than the child. Stdin goes through a feeder thread that waits in select for room in the pipe, with the descriptor switched to non-blocking and written in 64 KiB chunks, so a child that never reads cannot freeze the call before the deadline is consulted – the first of the bugs below. The thread never closes the descriptor: the main thread closes it once, after stop_and_join() has proved the thread has stopped using it, which removes the close race the earlier version had. On a deadline the group is signalled; both drains are then joined against one shared bound – two pipes are given the bound once, not once each, which is what keeps the two runners on the same clock – and if a drain is still alive after it, it is stopped and the result is marked escaped, which is the case section 12 measured where a process outside the group holds the pipe. drain_after_exit_s is that bound, and reap_group=True extends the group kill to a clean exit for callers who want the tree finished, not just the child.
"""A runner that drains every pipe and kills the whole tree on a deadline."""
from __future__ import annotations
import os
import select
import subprocess
import threading
import time
from dataclasses import dataclass, field
from .group import group_members, kill_group
from .pipe import Drain, set_pipe_capacity
DEFAULT_LIMIT = 8 << 20
POLL_S = 0.002
DRAIN_JOIN_S = 1.0
FEED_CHUNK = 65536
@dataclass(frozen=True)
class Captured:
"""What a finished child produced, and what it cost to collect it."""
returncode: int
stdout: bytes
stderr: bytes
elapsed_s: float
timed_out: bool = False
truncated: bool = False
escaped: bool = False
stdin_sent: int = 0
stdin_thread_alive: bool = False
kill: dict = field(default_factory=dict)
class _StdinFeeder(threading.Thread):
"""Write stdin from its own thread, so a child that never reads cannot hang the caller.
A blocking ``stdin.write`` of more than a pipe holds waits for the child to
read. On its own thread that wait is bounded by the runner's deadline instead
of freezing the call before the deadline is even consulted. The descriptor is
switched to non-blocking and written in chunks after ``select`` says there is
room, so ``stop()`` is seen within one poll period instead of at an arbitrary
point inside a blocking write.
The thread never closes the descriptor it writes to. Closing it there raced the
main thread, which closes the same fd after the run; the owner is the caller,
and ``stop_and_join`` is the handshake that says the thread has stopped using it.
"""
def __init__(self, stdin, data: bytes, poll_s: float = 0.05) -> None:
super().__init__(daemon=True)
self.stdin = stdin
self.data = memoryview(data)
self.poll_s = poll_s
self.sent = 0
self.error: BaseException | None = None
self.finished = False
self._stop_event = threading.Event()
def run(self) -> None:
fd = self.stdin.fileno()
try:
os.set_blocking(fd, False)
while self.sent < len(self.data) and not self._stop_event.is_set():
_, ready, _ = select.select([], [fd], [], self.poll_s)
if not ready:
continue
chunk = self.data[self.sent:self.sent + FEED_CHUNK]
try:
self.sent += os.write(fd, chunk)
except BlockingIOError:
continue
except (BrokenPipeError, OSError, ValueError) as exc:
self.error = exc
finally:
self.finished = True
def stop(self) -> None:
self._stop_event.set()
def stop_and_join(self, timeout_s: float = DRAIN_JOIN_S) -> bool:
"""Stop at the next poll and wait for the thread; True if it has ended."""
self._stop_event.set()
self.join(max(timeout_s, self.poll_s * 4))
return not self.is_alive()
def run_captured(argv, *, timeout: float | None = None, limit: int = DEFAULT_LIMIT,
merge: bool = False, pipesize: int | None = None,
stdin_bytes: bytes | None = None, cwd: str | None = None,
env: dict | None = None, drain_after_exit_s: float = DRAIN_JOIN_S,
reap_group: bool = False) -> Captured:
"""Run argv, read both pipes concurrently, and never wait on an unread pipe.
`timeout` is a wall-clock bound on the child, not on the read: when it expires the
process group is signalled, so a grandchild that inherited the pipe cannot keep
the runner waiting for an EOF that will not come. `limit` caps what is kept from
each stream; the rest is read and discarded so the child is never blocked by a
reader that stopped reading.
``drain_after_exit_s`` bounds what happens *after* the child exits: the readers
share that one bound - both are joined against the same deadline, not half a second
each - before the pipes are reported as abandoned (``escaped``). That is the same
rule the asyncio runner applies, so the two agree on a grandchild that outlives its
parent, including when a deadline fired first. ``reap_group=True`` signals the
whole session after a clean exit as well, which turns "the child is done" into
"the tree is done"; the default leaves a grandchild running, as a plain
``Popen`` does.
"""
started = time.perf_counter()
kwargs: dict = {
"stdin": subprocess.PIPE if stdin_bytes is not None else subprocess.DEVNULL,
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT if merge else subprocess.PIPE,
"bufsize": 0,
"start_new_session": True,
"cwd": cwd,
"env": env,
}
if pipesize is not None:
kwargs["pipesize"] = pipesize
process = subprocess.Popen(argv, **kwargs)
pgid = os.getpgid(process.pid)
out = Drain(process.stdout.fileno(), limit=limit)
err = None if merge else Drain(process.stderr.fileno(), limit=limit)
out.start()
if err is not None:
err.start()
feeder = None
if stdin_bytes is not None:
feeder = _StdinFeeder(process.stdin, stdin_bytes)
feeder.start()
timed_out = False
stdin_closed = False
deadline = None if timeout is None else started + timeout
while process.poll() is None:
if feeder is not None and feeder.finished and not stdin_closed:
# Everything has been written (or the write failed), so the child needs the
# EOF now: the owner closes the descriptor, not the feeder thread.
try:
process.stdin.close()
except OSError:
pass
stdin_closed = True
if deadline is not None and time.perf_counter() >= deadline:
timed_out = True
break
time.sleep(POLL_S)
kill_report: dict = {}
if timed_out:
kill_report = kill_group(pgid)
try:
process.wait(timeout=DRAIN_JOIN_S)
except subprocess.TimeoutExpired:
kill_report["wait_timed_out"] = True
elif reap_group:
kill_report = kill_group(pgid)
escaped = False
drains = [drain for drain in (out, err) if drain is not None]
# One deadline for every pipe: joining them in turn would let a two-pipe tree cost
# twice the bound, which is exactly the gap this runner is supposed to close.
drain_deadline = time.perf_counter() + drain_after_exit_s
for drain in drains:
drain.join(max(0.0, drain_deadline - time.perf_counter()))
if any(drain.is_alive() for drain in drains):
escaped = True # something outside the group still holds a pipe
for drain in drains:
drain.stop()
stop_deadline = time.perf_counter() + DRAIN_JOIN_S
for drain in drains:
drain.join(max(0.0, stop_deadline - time.perf_counter()))
stdin_thread_alive = False
if feeder is not None:
stdin_thread_alive = not feeder.stop_and_join()
if not stdin_closed and not stdin_thread_alive:
try:
process.stdin.close()
except OSError:
pass
stdin_closed = True
if process.poll() is None:
process.kill()
process.wait(timeout=DRAIN_JOIN_S)
returncode = process.returncode if process.returncode is not None else -1
streams = [process.stdout, process.stderr]
if not stdin_thread_alive and not stdin_closed: # the feeder has stopped using stdin
streams.insert(0, process.stdin)
for stream in streams:
if stream is not None:
try:
stream.close()
except OSError:
pass
elapsed = time.perf_counter() - started
truncated = any(d is not None and d.truncated for d in (out, err))
return Captured(
returncode=returncode,
stdout=out.bytes(),
stderr=b"" if err is None else err.bytes(),
elapsed_s=round(elapsed, 6),
timed_out=timed_out,
truncated=truncated,
escaped=escaped,
stdin_sent=0 if feeder is None else feeder.sent,
stdin_thread_alive=stdin_thread_alive,
kill=kill_report,
)
def widen_pipe(process, size: int) -> int:
"""Raise the capacity of a child's stdin pipe after it exists, and return the result."""
return set_pipe_capacity(process.stdin.fileno(), size)
def surviving(pgid: int) -> int:
"""How many live processes are left in a group, for a post-condition check."""
return len(group_members(pgid))
procguard/aio.py – the same guarantees for asyncio
The asyncio runner reads both pipes with its own bounded tasks, so limit caps what is kept instead of only sizing a stream buffer, and it kills the group with awaits rather than with time.sleep – the other two bugs below. It times out on the child’s own exit, which it detects from returncode rather than from Process.wait(): that method only resolves once every pipe is disconnected, so a grandchild holding stdout would keep it pending and the coroutine would wait for an EOF that never comes. For the same reason its kill path waits for the child’s own exit rather than for the transport to close, which is what a deadline on an escaped pipe used to stall on. After the child exits it gives the readers the same drain_after_exit_s the synchronous runner gives its drains, marks the pipe escaped if they do not reach EOF, and honours reap_group on the way out – so the two runners return the same verdict on the same tree.
"""The same guarantees for asyncio, where the waits are the part that misbehaves."""
from __future__ import annotations
import asyncio
import contextlib
import os
import signal
from dataclasses import dataclass
from .group import group_members
WAIT_LIMIT_S = 2.0
POLL_S = 0.005
DRAIN_AFTER_EXIT_S = 1.0
CHUNK = 65536
@dataclass(frozen=True)
class AsyncCaptured:
"""The asyncio equivalent of Captured: output, status, and how the cleanup ended."""
returncode: int
stdout: bytes
stderr: bytes
elapsed_s: float
timed_out: bool = False
truncated: bool = False
escaped: bool = False
wait_resolved: bool = True
kill: dict | None = None
async def _wait_empty_async(pgid: int, timeout_s: float, poll_s: float = POLL_S) -> float | None:
"""Seconds until the group holds no live process, or None - awaited, not slept."""
loop = asyncio.get_running_loop()
started = loop.time()
while loop.time() - started < timeout_s:
if not group_members(pgid):
return loop.time() - started
await asyncio.sleep(poll_s)
return None
async def _kill_group_async(pgid: int, *, grace_s: float = 0.5,
poll_s: float = POLL_S) -> dict:
"""SIGTERM the group, wait, then SIGKILL whatever is left - without blocking the loop.
The synchronous ``kill_group`` polls with ``time.sleep``, which freezes every
other coroutine for as long as the grace period lasts. The waits here are
``await asyncio.sleep``; the only synchronous part is reading /proc.
"""
loop = asyncio.get_running_loop()
report = {"pgid": pgid, "members_before": len(group_members(pgid)),
"sent": [], "survivors": 0, "empty_s": None, "escalated": False}
started = loop.time()
try:
os.killpg(pgid, signal.SIGTERM)
report["sent"].append("SIGTERM")
except ProcessLookupError:
report["empty_s"] = 0.0
return report
empty_s = await _wait_empty_async(pgid, grace_s, poll_s)
if empty_s is not None:
report["empty_s"] = round(empty_s, 3)
return report
report["escalated"] = True
try:
os.killpg(pgid, signal.SIGKILL)
report["sent"].append("SIGKILL")
except ProcessLookupError:
report["empty_s"] = round(loop.time() - started, 3)
return report
empty_s = await _wait_empty_async(pgid, grace_s, poll_s)
report["empty_s"] = None if empty_s is None else round(empty_s, 3)
report["survivors"] = len(group_members(pgid))
return report
async def _read_bounded(reader, limit: int, sink: bytearray) -> bool:
"""Read to EOF, keeping `limit` bytes and draining the rest. Returns truncation.
A chunk that fits is appended without a slice, so the common case copies the
bytes once instead of twice; only the chunk that crosses the cap is cut.
"""
truncated = False
while True:
chunk = await reader.read(CHUNK)
if not chunk:
return truncated
room = limit - len(sink)
if room > 0:
sink += chunk if len(chunk) <= room else chunk[:room]
if len(chunk) > room:
truncated = True
async def _stop(process, grace_s: float) -> tuple[dict, bool]:
"""Kill the child's group, then wait for the child itself to be reported dead.
The wait is on ``returncode``, not on ``Process.wait()``: the latter only resolves
once every pipe is disconnected, so a pipe an escaped grandchild still holds would
keep it pending for the full ``WAIT_LIMIT_S`` while the synchronous runner had
already moved on. Waiting for the exit keeps the two runners on the same clock
when a deadline fires. ``wait_resolved`` records whether that wait succeeded; if
it did not, the transport is closed so the pipes are released anyway.
"""
pgid = os.getpgid(process.pid)
report = await _kill_group_async(pgid, grace_s=grace_s)
try:
await asyncio.wait_for(_wait_returncode(process), WAIT_LIMIT_S)
resolved = True
except asyncio.TimeoutError:
resolved = False
transport = getattr(process, "_transport", None)
if transport is not None:
transport.close()
return report, resolved
async def _wait_returncode(process) -> int:
"""Wait for the child itself to exit, not for its pipes to close.
``Process.wait()`` resolves in ``_call_connection_lost``, which asyncio only
reaches once every pipe is disconnected - so a grandchild holding stdout keeps
it pending long after the child is gone. ``returncode`` is filled in when the
child is reaped, which is the event this runner has to time out on.
"""
while process.returncode is None:
await asyncio.sleep(POLL_S)
return process.returncode
async def run_async(argv, *, timeout: float | None = None, limit: int = 8 << 20,
merge: bool = False, drain_after_exit_s: float = DRAIN_AFTER_EXIT_S,
reap_group: bool = False) -> AsyncCaptured:
"""Run argv with two pipes read concurrently, bounded by `timeout` and by `limit`.
`limit` is a capture cap, not the stream buffer: the readers copy at most
`limit` bytes into the result and keep draining so the child is never blocked
by a reader that stopped reading. The buffer limit passed to the subprocess is
only the size of a single read.
The order is the synchronous runner's: wait for the child up to `timeout`, then
give the readers `drain_after_exit_s` to reach EOF and mark the pipe `escaped`
if they do not. The two runners therefore give the same verdict on the same tree,
and each waits one bound for the readers rather than one per pipe: measured on
three trees, their medians stayed within a few tens of milliseconds of each other.
A coroutine that waited for an EOF nobody would send is what this replaces.
`reap_group=True` signals the session after a clean exit too, so a successful call
cannot leave a tree behind.
"""
loop = asyncio.get_running_loop()
started = loop.time()
process = await asyncio.create_subprocess_exec(
*argv,
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT if merge else asyncio.subprocess.PIPE,
start_new_session=True,
limit=CHUNK,
)
pgid = os.getpgid(process.pid)
out, err = bytearray(), bytearray()
readers = [asyncio.create_task(_read_bounded(process.stdout, limit, out))]
if not merge:
readers.append(asyncio.create_task(_read_bounded(process.stderr, limit, err)))
exit_watch = asyncio.create_task(_wait_returncode(process))
timed_out = False
kill_report = None
wait_resolved = True
escaped = False
try:
done, pending = await asyncio.wait({exit_watch}, timeout=timeout)
if exit_watch in pending:
timed_out = True
kill_report, wait_resolved = await _stop(process, grace_s=0.5)
elif reap_group:
kill_report = await _kill_group_async(pgid, grace_s=0.5)
finished, stuck = await asyncio.wait(readers, timeout=drain_after_exit_s)
if stuck:
escaped = True # a process outside the group still holds the pipe
for task in stuck:
task.cancel()
if escaped:
wait_resolved = False
transport = getattr(process, "_transport", None)
if transport is not None:
transport.close()
else:
try:
await asyncio.wait_for(process.wait(), WAIT_LIMIT_S)
except asyncio.TimeoutError:
wait_resolved = False
transport = getattr(process, "_transport", None)
if transport is not None:
transport.close()
finally:
for task in (*readers, exit_watch):
if not task.done():
task.cancel()
await asyncio.gather(*readers, return_exceptions=True)
await asyncio.gather(exit_watch, return_exceptions=True)
results = [task.result() for task in readers if not task.cancelled()
and task.exception() is None]
truncated = any(result is True for result in results)
elapsed = loop.time() - started
return AsyncCaptured(
returncode=process.returncode if process.returncode is not None else -1,
stdout=bytes(out[:limit]),
stderr=bytes(err[:limit]),
elapsed_s=round(elapsed, 6),
timed_out=timed_out,
truncated=truncated,
escaped=escaped,
wait_resolved=wait_resolved,
kill=kill_report,
)
@contextlib.asynccontextmanager
async def spawn(argv, *, merge: bool = False):
"""A subprocess whose tree is killed and reaped however the block ends."""
process = await asyncio.create_subprocess_exec(
*argv,
stdin=asyncio.subprocess.DEVNULL,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.STDOUT if merge else asyncio.subprocess.PIPE,
start_new_session=True,
)
try:
yield process
finally:
if process.returncode is None:
await _stop(process, grace_s=0.5)
else:
try:
await asyncio.wait_for(process.wait(), WAIT_LIMIT_S)
except asyncio.TimeoutError:
pass
def leftovers(pgid: int) -> int:
"""Live processes a group still holds, used by the tests as a post-condition."""
return len(group_members(pgid))
procguard/__init__.py – the public surface
Everything the module exposes is listed here. There is no private helper the article calls without printing: the five files above are the whole package, which is what makes the measurements in Table 15 reproducible by copying them.
"""Bounded subprocess execution: capture without deadlock, and a deadline that ends the session.
The package is small on purpose. Each module answers one failure mode measured in
the article: a pipe that has to be drained (``pipe``), a tree that has to be killed
by group (``group``), and a runner that does both within a deadline (``run``, ``aio``).
A clean exit is left alone: a grandchild that outlives its parent keeps running, as
it does with a plain ``Popen``, unless the caller passes ``reap_group=True``. What
is guaranteed without asking is the deadline: when ``timeout`` fires, the whole
session is signalled and drained before the call returns, so nothing left in that
session is holding the pipe. A process that left the session is the exception, and
it is reported rather than denied: the call returns with ``escaped`` set.
"""
from __future__ import annotations
from .aio import run_async, spawn
from .group import group_members, kill_group, proc_state, terminate_tree
from .pipe import F_GETPIPE_SZ, F_SETPIPE_SZ, Drain, pipe_capacity, set_pipe_capacity
from .run import Captured, run_captured
__version__ = "0.1.0"
__all__ = [
"Captured",
"Drain",
"F_GETPIPE_SZ",
"F_SETPIPE_SZ",
"group_members",
"kill_group",
"pipe_capacity",
"proc_state",
"run_async",
"run_captured",
"set_pipe_capacity",
"spawn",
"terminate_tree",
]
The three bugs the first version shipped with
The first version of this runner had three defects, and they are worth printing because each one is a failure this article describes, written by the article’s own code. The probe below is the one that caught the first: it writes 1 MiB to the stdin of a child that never reads, the way the original runner did before it looked at the clock.
from __future__ import annotations
import subprocess
import threading
from common import PYTHON
NOT_READING = "import time; time.sleep(30)"
PAYLOAD = 1 << 20
def old_pattern(payload_size: int = PAYLOAD, patience: float = 1.5) -> dict:
"""What the first version did: write 1 MiB to a child that never reads it."""
child = subprocess.Popen([PYTHON, "-c", NOT_READING], stdin=subprocess.PIPE, bufsize=0)
done = threading.Event()
state: dict = {"sent": 0, "error": None}
def writer() -> None:
try:
state["sent"] = child.stdin.write(b"s" * payload_size)
except (BrokenPipeError, OSError) as exc:
state["error"] = type(exc).__name__
finally:
done.set()
thread = threading.Thread(target=writer, daemon=True)
thread.start()
completed = done.wait(patience)
report = {"payload_bytes": payload_size, "patience_s": patience,
"write_completed": completed, "sent_bytes": state["sent"]}
child.kill()
child.wait()
done.wait(2.0)
report["error_after_kill"] = state["error"]
report["sent_bytes_after_kill"] = state["sent"]
try:
child.stdin.close()
except OSError:
pass
thread.join(timeout=1)
return report
The write did not complete within the probe’s 1.5-second patience: the call was inside write(2), before the runner’s deadline loop had run once, and the bytes it reported were 0 because the syscall had not returned. After the child was killed the call returned having written 65,536 bytes – a short write the caller would have had to notice, which is the exception to the all-or-fail rule of section 9: that rule holds while the reader lives. The fixed runner returns at 507.5 ms with timed_out set, having delivered the 65,536 bytes the pipe would take; a child that does read receives all 1,048,576 bytes in 16.0 ms.
The second bug was in the asyncio kill: the grace period polled with time.sleep, which stops every other coroutine. The probe counts ticks of a 10 ms ticker while a 0.5 s blocking sleep runs and while the new awaited kill runs: 0 ticks against 67, over a kill that took 0.71 s and escalated to SIGKILL. The third was limit: passing it to StreamReader only sets the read buffer, so a 1 MiB child was captured in full. With the reader capping the sink itself, the same child yields 1,024 bytes and a truncation flag.
Each of the earlier three has a test in tests/test_regressions.py, printed here in full beside the tests for the fixes in this section: the feeder’s handshake and its thread count, the escaped pipe in both runners, reap_group on a clean exit, and a deadline that a group kill can and cannot satisfy. They are the reason a later change cannot quietly reintroduce the hang: the tests assert that the call returns inside its deadline, that a child that reads still receives every byte, and that no thread survives the return. The file imports its child sources and its cleanup helpers from conftest.py, so that file is printed in full beside it as well. Those two files are the whole of what this section shows of the suite: the four other test modules hold 47 of the 60 tests and are not reproduced here, so what is reproducible from this page is the regression file and its fixtures, not every test the count refers to.
The cleanup helper in conftest.py had the same defect the probe had in section 7, which is the other reason it is printed. It searched command lines for a marker string, and that string sat inside the tree’s own source – so it was in the spawner’s command line too, and a scan returned the spawner, the process under test, as a leftover to kill. The reap tests passed anyway, because the spawner had already exited by the time they asserted. It now reads a tag the grandchild writes into its own comm, exactly as the probe does, and test_the_cleanup_helper_never_names_the_process_under_test pins that the spawner is never in the set.
"""Fixtures shared by the procguard tests: paths, child scripts, and the one way a test
names a process it did not start itself."""
from __future__ import annotations
import os
import pathlib
import sys
import time
import pytest
ROOT = pathlib.Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
PY = sys.executable
# 1 MiB to stdout and 1 MiB to stderr, 64 KiB at a time.
BOTH_PIPES = ('import os, sys\nchunk = b"o" * 65536\n'
"for _ in range(16):\n os.write(1, chunk)\n os.write(2, chunk)\n")
# A child, a grandchild that inherits stdout, and a long sleep.
TREE = ('import subprocess, sys, time\n'
'subprocess.Popen([sys.executable, "-c", "import time; time.sleep(5)"])\n'
'print("ready", flush=True)\n'
"time.sleep(30)\n")
# The two tags a test's grandchild writes into its own /proc/<pid>/comm before it sleeps.
# Nine to thirteen bytes, because the kernel keeps at most fifteen there.
ESCAPE_TAG = "prcguard-esc"
REAP_TAG = "prcguard-reap"
# The same tree as TREE, but the grandchild leaves the session so a group kill cannot
# reach it - and carries ESCAPE_TAG, which is how the test finds it again. The tag is not
# passed through the spawner's ``-c`` source: that would put it in the spawner's own
# command line, and a scan for it would return the parent as well.
ESCAPING_GRANDCHILD = ("import time\nopen('/proc/self/comm','w').write('"
+ ESCAPE_TAG + "')\ntime.sleep(5)")
ESCAPED = ('import subprocess, sys\n'
'subprocess.Popen([sys.executable, "-c", ' + repr(ESCAPING_GRANDCHILD) + '],\n'
' start_new_session=True)\n'
'print("ready", flush=True)\n')
IGNORES_TERM = ('import signal, time\n'
'signal.signal(signal.SIGTERM, lambda *a: None)\n'
'print("ready", flush=True)\n'
"time.sleep(30)\n")
# A group with exactly two live members: the leader and one child.
TWO_MEMBERS = ('import subprocess, sys, time\n'
'subprocess.Popen([sys.executable, "-c", "import time; time.sleep(3)"])\n'
'print("ready", flush=True)\n'
"time.sleep(3)\n")
@pytest.fixture()
def python() -> str:
return PY
def tagged_pids(tag: str) -> list[int]:
"""Live processes whose /proc/<pid>/comm is exactly `tag`, which they wrote themselves.
The earlier version of this helper searched command lines for a marker, and a marker
placed inside a child source is inside that child's own command line too: a scan for
it returned the spawner - the process under test - before the grandchild it was
looking for. A killed process also keeps its comm until somebody reaps it, and this
container reaps nothing, so the live check is what keeps a cleaned-up test clean.
"""
found = []
for entry in pathlib.Path("/proc").iterdir():
if not entry.name.isdigit():
continue
try:
comm = pathlib.Path(f"/proc/{entry.name}/comm").read_text().strip()
state = pathlib.Path(f"/proc/{entry.name}/stat").read_text()
except (FileNotFoundError, ProcessLookupError, OSError):
continue
if comm == tag and state[state.rfind(")") + 2:].split()[0] != "Z":
found.append(int(entry.name))
return sorted(found)
def kill_tagged(tag: str) -> None:
"""Kill every live process that carries `tag`, retrying while one is still arming."""
import signal
for _ in range(5):
found = tagged_pids(tag)
if not found:
return
for pid in found:
try:
os.kill(pid, signal.SIGKILL)
except OSError:
pass
time.sleep(0.02)
"""The bugs the first drafts of procguard shipped with, each as a test.
They are here rather than in test_run.py and test_aio.py because each one is a
regression: the code failed in exactly this way, and the test is the thing that
says it cannot fail that way again.
"""
from __future__ import annotations
import asyncio
import subprocess
import sys
import threading
import time
from conftest import IGNORES_TERM, REAP_TAG, kill_tagged, tagged_pids
from procguard.aio import run_async
from procguard.run import run_captured
PY = sys.executable
# A child that starts a grandchild inheriting stdout and exits at once, so the pipe
# outlives the process the runner is waiting for. The grandchild ends by itself.
ORPHANING = ('import subprocess, sys\n'
'subprocess.Popen([sys.executable, "-c", "import time; time.sleep(1.2)"])\n'
'print("started", flush=True)\n')
# The same tree with a tag its grandchild writes into its own comm, and a long enough
# sleep for a reap test to be exact. The tag is not in this source: a tag passed through
# ``-c`` is in the spawner's command line too, which is how the earlier version of this
# file matched the spawner and then killed the process it was measuring.
REAPING_GRANDCHILD = ("import time\nopen('/proc/self/comm','w').write('"
+ REAP_TAG + "')\ntime.sleep(9)")
HOLDING = ('import subprocess, sys\n'
'subprocess.Popen([sys.executable, "-c", '
+ repr(REAPING_GRANDCHILD) + '])\n'
'print("started", flush=True)\n')
# A tree that is still running when the deadline fires, with the grandchild inside the
# group (a group kill reaches it) and with the grandchild outside it (nothing does).
RUNNING = ('import subprocess, sys, time\n'
'subprocess.Popen([sys.executable, "-c", "import time; time.sleep(2.5)"])\n'
'print("ready", flush=True)\n'
'time.sleep(30)\n')
ESCAPING = ('import subprocess, sys, time\n'
'subprocess.Popen([sys.executable, "-c", "import time; time.sleep(2.5)"],\n'
' start_new_session=True)\n'
'print("ready", flush=True)\n'
'time.sleep(30)\n')
def test_stdin_larger_than_a_pipe_does_not_hang_a_child_that_ignores_it():
"""A blocking stdin.write of 1 MiB froze before the deadline was ever checked."""
started = time.perf_counter()
result = run_captured([PY, "-c", "import time; time.sleep(30)"], timeout=0.5,
stdin_bytes=b"s" * (1 << 20))
assert result.timed_out is True
assert result.escaped is False
assert time.perf_counter() - started < 5
def test_stdin_of_one_mebibyte_is_delivered_in_full():
"""The fix must not trade the hang for silent truncation of the input."""
code = "import sys\ndata = sys.stdin.buffer.read()\nprint(len(data))"
result = run_captured([PY, "-c", code], timeout=10, stdin_bytes=b"q" * (1 << 20))
assert result.stdout.strip() == b"1048576"
assert result.stdin_sent == 1 << 20
def test_a_stopped_feeder_leaves_no_thread_and_no_closed_fd_race():
"""The feeder used to close stdin itself while the main thread closed it too."""
before = threading.active_count()
result = run_captured([PY, "-c", "import time; time.sleep(5)"], timeout=0.3,
stdin_bytes=b"s" * (4 << 20))
assert result.timed_out is True
assert result.stdin_thread_alive is False
time.sleep(0.2)
assert threading.active_count() <= before
def test_an_escaped_pipe_is_reported_and_leaves_no_reader_thread():
"""A grandchild holding the pipe must not become a thread nobody can stop."""
before = threading.active_count()
result = run_captured([PY, "-c", ORPHANING], timeout=None, drain_after_exit_s=0.2)
assert result.escaped is True
assert result.elapsed_s < 2
time.sleep(0.2)
assert threading.active_count() <= before
def test_sync_and_async_agree_when_a_grandchild_outlives_the_child():
"""The asyncio runner used to wait for an EOF the escaped pipe never sent."""
sync = run_captured([PY, "-c", ORPHANING], timeout=None, drain_after_exit_s=0.3)
started = time.perf_counter()
async_ = asyncio.run(run_async([PY, "-c", ORPHANING], timeout=None,
drain_after_exit_s=0.3))
async_elapsed = time.perf_counter() - started
assert sync.escaped is True
assert async_.escaped is True
assert async_elapsed < 3
assert abs(sync.elapsed_s - async_elapsed) < 1.5
def test_sync_and_async_agree_when_the_deadline_fires_inside_the_group():
"""A deadline on a tree a group kill can reach: both runners end at the deadline."""
sync = run_captured([PY, "-c", RUNNING], timeout=0.5, drain_after_exit_s=0.3)
started = time.perf_counter()
async_ = asyncio.run(run_async([PY, "-c", RUNNING], timeout=0.5, drain_after_exit_s=0.3))
async_elapsed = time.perf_counter() - started
assert sync.timed_out is True and async_.timed_out is True
assert sync.escaped is False and async_.escaped is False
assert sync.kill["survivors"] == 0 and async_.kill["survivors"] == 0
assert abs(sync.elapsed_s - async_elapsed) < 0.3
def test_sync_and_async_agree_when_the_deadline_fires_and_the_pipe_is_escaped():
"""The same deadline with a grandchild the group cannot reach: one shared drain bound."""
sync = run_captured([PY, "-c", ESCAPING], timeout=0.5, drain_after_exit_s=0.3)
started = time.perf_counter()
async_ = asyncio.run(run_async([PY, "-c", ESCAPING], timeout=0.5, drain_after_exit_s=0.3))
async_elapsed = time.perf_counter() - started
assert sync.timed_out is True and async_.timed_out is True
assert sync.escaped is True and async_.escaped is True
# Two pipes joined one after the other used to cost twice this bound in the sync
# runner, which is the gap this test pins: the difference is inside a third of a second.
assert abs(sync.elapsed_s - async_elapsed) < 0.35
def test_the_cleanup_helper_never_names_the_process_under_test():
"""A marker inside HOLDING is inside HOLDING's own command line too.
The old helper searched command lines, so it found the spawner first and would have
killed the process the test was measuring; it only looked correct because the spawner
had already exited by the time the reap tests asserted. The tag now lives in the
grandchild's own comm, so the spawner is never in the set.
"""
child = subprocess.Popen([PY, "-c", HOLDING], stdout=subprocess.PIPE)
try:
child.stdout.readline()
deadline = time.perf_counter() + 5
while not tagged_pids(REAP_TAG) and time.perf_counter() < deadline:
time.sleep(0.02)
found = tagged_pids(REAP_TAG)
assert found, "the tagged grandchild never appeared"
assert child.pid not in found
finally:
kill_tagged(REAP_TAG)
child.kill()
child.wait()
child.stdout.close()
def test_reap_group_ends_the_tree_after_a_clean_exit():
"""`reap_group=True` is the option that makes a clean exit mean a clean tree."""
try:
result = run_captured([PY, "-c", HOLDING], timeout=None, reap_group=True)
assert result.timed_out is False
assert result.escaped is False
assert result.kill["survivors"] == 0
assert tagged_pids(REAP_TAG) == []
finally:
kill_tagged(REAP_TAG)
def test_without_reap_group_a_clean_exit_leaves_the_grandchild_alone():
"""The default is Popen's: a finished child does not end its descendants."""
try:
result = run_captured([PY, "-c", HOLDING], timeout=None, drain_after_exit_s=0.2)
assert result.escaped is True
assert tagged_pids(REAP_TAG) != []
finally:
kill_tagged(REAP_TAG)
def test_reap_group_works_the_same_way_in_the_asyncio_runner():
try:
async_ = asyncio.run(run_async([PY, "-c", HOLDING], timeout=None, reap_group=True))
assert async_.timed_out is False
assert async_.escaped is False
assert async_.kill["survivors"] == 0
assert tagged_pids(REAP_TAG) == []
finally:
kill_tagged(REAP_TAG)
def test_async_limit_caps_the_capture_and_flags_it():
"""`limit` used to size a stream buffer; a 1 MiB child was captured in full."""
code = 'import os; os.write(1, b"x" * (1 << 20))'
result = asyncio.run(run_async([PY, "-c", code], timeout=10, limit=1024))
assert len(result.stdout) == 1024
assert result.truncated is True
def test_async_group_kill_keeps_the_event_loop_running():
"""The grace period used time.sleep, so no other coroutine ran during it."""
async def scenario() -> tuple[int, object]:
ticks = 0
async def ticker() -> None:
nonlocal ticks
while True:
await asyncio.sleep(0.01)
ticks += 1
task = asyncio.create_task(ticker())
try:
result = await run_async([PY, "-c", IGNORES_TERM], timeout=0.2)
finally:
task.cancel()
return ticks, result
ticks, result = asyncio.run(scenario())
assert result.timed_out is True
assert result.kill["escalated"] is True
assert ticks >= 15 # 0.2 s deadline plus a 0.5 s grace, at 10 ms a tick
Against the failures of this article the module gives one line each. Two 1 MiB streams are captured in 15.2 ms with no deadlock and no truncation. A tree with a grandchild holding the pipe and a half-second deadline returns at 506.3 ms with 0 survivors, one signal sent (SIGTERM) and no escalation. Sixty-four MiB of output moves at 697.8 MiB/s with the default capture limit raised – the median of seven runs that spanned 194.8 to 756.3 – and the asyncio path captures the same two 1 MiB streams in 17.9 ms.
That spread is worth reading rather than smoothing away, because it belongs to the host and not to the runner. The parent’s own CPU time for those seven transfers moved with them, from 70.4 to 314.2 ms, while the accumulation every transfer performs – the same bytes taken 64 KiB at a time – stayed between 22.7 and 24.7 ms when measured without a pipe. Reads and copies therefore cost several times more CPU on some runs than on others. Steal time was not measured here, so the cause is not identified: what the seven runs show is that the parent’s CPU time moves with the wall clock from run to run, which is consistent with another tenant on the same host competing for the CPU, and inconsistent with the runner doing different work. The same code can be quoted at 194.8 MiB/s or at 756.3 MiB/s depending on the minute, so the figure is an order of magnitude rather than a benchmark.
The same three paths section 7 opened – no deadline, a deadline that a group kill can satisfy, and a deadline on a pipe an escaped grandchild still holds – were then run under both runners, three times each, with the readers given 0.3 s after the child. The medians are 375.9 ms against 327.6 ms without a deadline, 507.3 against 508.6 ms when the group kill reaches the tree, and 852.9 against 808.4 ms when it does not. The largest gap between the two is 48.3 ms, so “the same elapsed” is a measurement within that bound and not a claim of equality: the sync runner pays a few tens of milliseconds on an escaped pipe for stopping two reader threads, and the asyncio runner reports escaped without waiting for a transport that will never close. Before this section’s fix the same escaped case cost the sync runner twice the reader bound, because its two drains were joined one after the other.
| Case | Result | Failure it rules out |
|---|---|---|
Two 1 MiB pipes, run_captured | 1,048,576 + 1,048,576 bytes, 15.2 ms | the read-order deadlock |
| 1 MiB of stdin into a child that ignores it | returned at 507.5 ms, 65,536 bytes sent | the stdin deadlock that preceded the deadline |
| Tree with a pipe-holding grandchild, half-second deadline | returned 506.3 ms, 0 survivors | the timeout that leaves the tree |
| Same case, asyncio | 1,048,576 bytes from each stream, 17.9 ms | the abandoned transport |
| 64 MiB of output | 697.8 MiB/s (194.8 – 756.3), 67,108,864 bytes captured | the capture that silently truncates |
1 MiB of output with limit=1024 | 1,024 bytes kept, truncation flagged | a limit that only sized a buffer |
spawn context manager, exit with the child alive | the child is killed and reaped by the time the block returns | a leak on the error path |
| Whole suite | 60 tests | everything above, on every change |
The package is 731 lines across 36 + 98 + 126 + 225 + 246 lines, with 60 tests split 10 for the pipe, 15 for groups, 13 for the runner, 9 for asyncio and 13 for the regressions. They run in a few seconds because every test is a real process on this machine: the timeout tests spend half a second each, and nothing is mocked.
| File | Lines | Tests | What it is responsible for |
|---|---|---|---|
pipe.py | 98 | 10 | capacity, filling, a stoppable drain |
group.py | 126 | 15 | membership, escalation, the shared-group trap |
run.py | 225 | 13 | the synchronous runner, its stdin feeder and its capture limit |
aio.py | 246 | 9 | the asyncio runner, an awaited kill, bounded reads |
__init__.py | 36 | 0 | the public names, nothing else |
tests/test_regressions.py | part of the suite | 13 | the earlier bugs and the fixes for the feeder, the escaped pipe and reap_group |
| total | 731 | 60 | all of the above |
What is in the box: The package is kept with the measurement suite and is not published in a public repository yet, so the tables above are the record of its behaviour rather than a promise about a release. Everything it does is printed in this section; nothing is hidden in a private helper that the article declines to show.
15. The cheapest fix, and the ones outside Python
Every section so far assumed the child’s output has to come back through a pipe. Often it does not, and the cheapest fix is to stop asking for a pipe rather than to manage one well. The first three alternatives below were measured on the same host with the same 32 MiB child, so they can be compared with the pipe they replace; the fourth is the supervisor’s version of the same idea and is described from its documentation.
If the output does not matter: /dev/null
The child writes 32 MiB to /dev/null and the parent captures nothing. That took 15.5 ms, against 59.1 ms for the same child through a captured pipe, and it is the only option here that cannot deadlock by construction: nothing is buffered, so nothing can fill. What it gives up is the output, which is fine for a command whose exit status is the whole result and wrong for anything a human will read. subprocess.DEVNULL is the one-line version, and it is the first thing to reach for when a service hangs while capturing output it never looks at.
If the output matters but not live: a temporary file
Pointing the child’s stdout at a file and reading it afterwards removes the pipe entirely: the write cost was 33.5 ms for 32 MiB, the read-back 38.5 ms. That is more than the 59.1 ms the pipe took, so the file is not a speed fix – it is a correctness fix. Nothing blocks on a file, the output survives a crash of the parent, and a child that writes gigabytes fails on disk space instead of on a buffer. The costs are the disk, the cleanup, the read-back, and a filesystem that can fill; on a machine where the output is large and the reader is optional, that trade is usually worth it.
If the problem is the tree: PR_SET_PDEATHSIG
When the failure is not the pipe but the process that outlives its parent, Linux has a per-process answer: prctl(PR_SET_PDEATHSIG, SIGKILL) asks the kernel to signal that process when its parent dies. The probe arms a grandchild this way, kills the middle process, and watches: the grandchild was a zombie 1.2 ms later, with no signal sent to the grandchild by the parent at all. The block below is the probe’s copy of that child’s source, string and all: it is what the probe passed to -c.
from __future__ import annotations
ARMED_SPAWNER = """
import ctypes, subprocess, sys, time
libc = ctypes.CDLL(None, use_errno=True)
def arm():
libc.prctl(1, 9, 0, 0, 0) # PR_SET_PDEATHSIG, SIGKILL
child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"],
preexec_fn=arm, start_new_session=True)
print(child.pid, flush=True)
time.sleep(30)
"""
Why this probe is not a pattern to copy: That child arms itself through preexec_fn, which is the shortest way to demonstrate PR_SET_PDEATHSIG and the wrong way to ship it. The subprocess documentation states the reason: preexec_fn is not safe in the presence of threads. The child is created by fork, which copies only the calling thread, so a lock another thread held at that instant stays held in the child; the callback then runs after fork and before exec, where only async-signal-safe work is legal – an allocation, a logging call, an import or a lock acquisition behind it can deadlock the child before the exec that would have fixed everything. The same documentation recommends the alternative: keep the arming in a small C wrapper or a posix_spawn wrapper that the launcher starts as a binary, or confine it to a single-threaded launcher process that does nothing else, and have the Python side spawn only that. CPython has since deprecated the parameter for this reason, and a service that sets it from a thread pool is the case the warning is about.
Three limits are worth knowing before relying on it. The setting is not inherited: the probe’s armed process was killed, and the child it had started kept running, because a process must arm itself. It is a signal, not a cleanup – nothing reaps the dead child, so a service that uses it still needs a reaper. And it is per thread on the parent side: the signal is sent when the thread that created the child exits, which in a threaded server is not necessarily when the process does. It is also Linux-only, and it is cleared when the next exec is a set-user-ID binary.
If the whole unit must stop: the cgroup
A supervisor’s stop is the coarser version of the same idea. systemd’s default KillMode=control-group sends the stop signal to every process in the unit’s control group, not just the main pid, and since a recent kernel a write of 1 to a cgroup’s cgroup.kill file kills every process in that cgroup. Either reaches processes that left the session, which is the case a group kill cannot cover. Neither can be measured here: this container runs no systemd unit and exposes no cgroup this probe may write to, so those two rows in Table 17 are described from their documentation rather than measured, and they are the only claims in this article that are not backed by a number in the results.
| Mechanism | Measured cost (32 MiB) | What it gives up |
|---|---|---|
| Pipe with a capped reader | 59.1 ms | a reader that has to exist, and a cap that has to be chosen |
/dev/null | 15.5 ms | the output itself |
| Temporary file | 33.5 ms write + 38.5 ms read-back | disk space, cleanup, and a full disk is a new failure mode |
PR_SET_PDEATHSIG | 1.2 ms to die | not inherited, no reaping, per-thread trigger, Linux-only |
systemd KillMode=control-group / cgroup.kill | not measured here | needs a unit or a cgroup you own and may write to |
16. The production runbook
The runbook is ordered by the cost of the check rather than the cost of the fix, because the first ten minutes of a hung subprocess are spent deciding which of seven failures it is, and most of them are cheap to rule out.
| Symptom | First check | Fix | Section |
|---|---|---|---|
| The call has not returned and CPU is idle | cat /proc/<child>/wchan; read wchar from /proc/<child>/io twice | Read both pipes at once – communicate(), or the two-drain runner | Section 4 |
The child is alive but wait() has not returned | Is wchar stuck at a multiple of the pipe size? Is any read outstanding? | Never wait without draining; wrap the pair in communicate() | Section 5 |
The process table shows Z entries | Count State: Z per parent; compare with the number of spawns | Reap with wait() or poll() on every path, including the error path | Section 6 |
| A timeout fires and the next request is slow too | Count descendants of the pid, not the pid; check whether the survivor holds a pipe | Start the child in its own session and signal the group | Sections 7 and 8 |
| A kill in an exception handler takes the worker down | Compare getpgid(child) with getpgid(0) | Only group-signal a child started with start_new_session=True, and make the helper refuse a group id of 0 or 1 | Section 8 |
| Descriptor count climbs with no leak in the code | Count /proc/self/fd against the number of live children | End the children; a descriptor is held until its child ends. Three per asyncio child | Sections 12 and 13 |
| Writes to a child are slow although the child is fast | Time a single write; look at the slowest write rather than the median | Smaller writes, a 262,144-byte pipe, or a reader that keeps up | Sections 9 and 10 |
| A handler stalls only in production and never in a test | Is the child’s output larger than 64 KiB in production and smaller in the test? | The test is the bug: it never filled a pipe | Section 3 |
Two rows are worth reading twice. The zombie row is the only one whose symptom appears long after the cause: a service can leak one pid per request for hours and then fail at a Popen that has nothing to do with the code that leaked it. And the last row is the reason this class of bug survives code review: a unit test with a child that prints three lines never fills a pipe, so the deadlock is created by the test’s own smallness.
The order to change a service
- Start every child in its own session, so the group is separable and a group signal cannot reach the service. If a helper is handed a group id, have it refuse 0 and 1 rather than calling
killpg: 0 is whatgetpgidreports for a group outside this namespace, andkillpg(0, ...)is a signal to your own group. - Never call
wait()on a process with unread pipes. Usecommunicate(), with a timeout, or the two-drain runner from section 14. - Send stdin from a thread or a non-blocking loop, never from the thread that is watching the clock: 1 MiB into a child that does not read is a hang of its own.
- On timeout, signal the group, wait a bounded grace period, escalate to SIGKILL, and then reap. Report the survivors instead of assuming zero.
- Reap on every path, including the exception path, and expose the count of state
Zchildren as a metric. - Cap the captured output. A truncation flag is better than an out-of-memory kill, and it is the only defence against a child that prints forever.
- If a child can outlive its caller, or if a grandchild can escape the group, stop waiting deliberately and mark the pipe as abandoned – the
escapedflag in section 14 – rather than blocking a worker thread forever.
The six-line version: None of this needs a library: Popen(..., start_new_session=True) plus communicate(timeout=...) plus os.killpg in the TimeoutExpired handler is six lines and removes the first five rows of the runbook. The module in section 14 exists for the sixth and seventh, where a plain communicate can be held open by a process it cannot see – and for the stdin case, where the write comes before the deadline.
17. What to put on a dashboard
A subprocess failure is invisible to a request timer and to a CPU graph. What makes it visible is a small set of counters that are cheap to sample from /proc and from the runner’s own return value.
- Live children per service, and the count of descriptors they hold – 307 for 100 children is the shape to expect, three per child.
- Children in state
Z, by parent. Any sustained non-zero value is a reaping bug, and it is the only early warning before pids run out. - Timeouts per minute and survivors per timeout. The first is the load signal, the second is the cleanup signal, and a timeout with zero survivors is a different event from one that leaves a tree.
- Bytes captured per call, as a histogram. A p99 above the pipe size is a call that filled a pipe at some point, which is the population in which deadlocks live.
- Slowest single write per child, not the median. The median is microseconds even on a fast path; the tail is where the reader’s pace appears.
- Captures marked
escapedortruncated, by child command. Both mean the runner did not get everything, and both are silent by default.
The one graph that ties them together is a scatter of captured bytes against call duration: calls that captured more than 64 KiB are the ones to sample when a hang is reported, because they are the only calls where the pipe was ever full. Everything below that line is a child whose output fit, and no amount of code review will tell those apart.
18. Frequently asked questions
How do I tell a subprocess deadlock from a slow child?
Look at two files in /proc. wchan names the kernel function the process is waiting in – a pipe wait means the child is blocked writing, not computing. io gives wchar, which should keep rising; if it is stuck at a multiple of 65,536 bytes, the pipe is full and the parent is not reading. In the measured case the parent had read 131,072 bytes and the child had written 196,608 when both stopped.
Why does subprocess.run(timeout=) leave processes behind?
Because it signals one pid. A child that started a grandchild has two processes, and the grandchild is not signalled: a 1-second timeout returned at 1.00 seconds and left 1 process running. Start the child with start_new_session=True and signal its group; the same tree then emptied 6.0 ms after the signal, with 0 survivors.
Is communicate() always safe?
It is safe against the read-order deadlock, because it drains both pipes at once: two 1 MiB streams arrived in 19.6 ms. It is not safe against a pipe whose write end is held by a process it cannot kill – a grandchild that inherited the descriptor kept the pipe open with no EOF for 1.5 seconds. Pair it with a timeout and a group kill, or use a runner that can abandon the pipe and say so.
Does close_fds=True prevent descriptors leaking into children?
It prevents accidental inheritance from the parent’s table: with 50 descriptors open, the child saw 4. It cannot prevent the three standard descriptors from being inherited, and a pipe connected to stdout is one of them, which is how a grandchild keeps a pipe alive. The measured holder count was 2 processes for one pipe.
How many zombies can a service accumulate?
One per child that exits and is never waited for, with no ceiling of its own. Twenty un-waited children produced 20 entries, and creating another Popen left 21 – the new child joined the queue and the creation reaped nothing; one poll() per child brought the count to 0. The limit is the pid space, and the failure at that limit appears somewhere else entirely.
Should I raise the pipe size?
Only for a child whose output you stream and whose writer you have measured. It helps: the same 32 MiB transfer ran at 1,294.1 MiB/s at the default size and 1,514.2 MiB/s at 1 MiB. It costs kernel memory per pipe, it does not prevent the deadlock, and it is capped at 1,048,576 bytes by /proc/sys/fs/pipe-max-size.
Why is a single write slow even when the child reads quickly?
Because the writer runs until the pipe is full and then waits for a slot. Even against a child that discards everything it reads, the slowest write in a 32 MiB transfer was about ten milliseconds (11.1 ms at 64 KiB chunks) while the median write was 16 us. The tail is the reader’s scheduling, not the child’s speed.
Does asyncio have the same problem?
Yes, with the same cause and a larger first bite: a sequential read in a coroutine stalled at 327,680 bytes, 5 pipe buffers, against 131,072 bytes in a thread, because the stream buffers on top of the pipe. The descriptor accounting is different: 307 descriptors for 100 live children, three each including a pidfd.
Why did writing a large stdin hang before the timeout?
Because the write happened first. A blocking stdin.write of 1 MiB into a child that does not read never returned: nothing had been accepted when the probe gave up after 1.5 seconds – the call was still inside the syscall – and the deadline was never consulted. The runner now feeds stdin from a thread and polls the clock itself, so the same child returns at 507.5 ms with a timeout flag; a child that reads receives all 1,048,576 bytes in 16.0 ms.
Is there a cheaper way than a pipe?
If you never look at the output, yes: /dev/null took 15.5 ms for 32 MiB against 59.1 ms for a captured pipe, and it cannot deadlock. If you look at it afterwards, a temporary file costs 33.5 ms to write and 38.5 ms to read back, more than the pipe but immune to a reader that never arrives. If the process outliving its parent is the problem, PR_SET_PDEATHSIG killed the grandchild in 1.2 ms.
19. What was verified, and what is out of scope
Every number in this article came from a probe executed on the host in Table 1. The probes are printed in the article; the results are kept as JSON beside them and rendered into the page by a build script rather than typed, so a figure that was never measured cannot appear. A second check then walks the prose, the tables and the FAQ and rejects any number that does not resolve to a recorded value.
The Python blocks were checked to be verbatim copies of the files that ran – not extracts edited for the page – and were then executed as printed. None of the probe blocks is a script: each one is the set of definitions its file holds, so executing it creates those functions and returns without doing anything else, and the program is the file’s entry function, which every probe file calls from a one-line if __name__ == "__main__": guard at its end. To run a block on its own: save it beside common.py, import it as a module and call the function that returns the record, or append the same guard. The package files are a different case. The runners call their siblings with relative imports, so they run inside procguard/ or not at all, and the regression tests are run by pytest with conftest.py beside them – both of which the article prints. Table 19 records which is which, because “save it and run it” is only true for some of them. Of the 60 tests, the 13 in the regression file and the fixtures they import are printed; the other 47 are not.
| Block | Source | What executing the block does | How it is run as a program |
|---|---|---|---|
Probe helpers (common.py) | sandbox/common.py | defines the helpers; nothing runs | imported by every probe beside it |
| Pipe capacity and fill helpers | sandbox/01_pipe_capacity.py | defines its functions | main() writes 01_pipe_capacity.json |
| Two-pipe reader and the sequential read | sandbox/02_deadlock.py | defines its functions | main() calls them with common.py on the path |
wait() without draining | sandbox/02_deadlock.py | defines its functions | the same file’s main() |
| Forked zombie and the twenty un-waited children | sandbox/04_zombie.py | defines its functions | main(), which uses own_zombies |
| Timeout with a grandchild holding the pipe, and the marker trap printed with it | sandbox/03_timeout.py | defines its functions | main(), which calls marker_trap() first, then with_inherited_pipe() and with_devnull_grandchild() with spawner, watch_grandchild and grandchild_pids |
| The group kill, the escalation of a group that ignores SIGTERM, and the measurement of what a shared group reads as | sandbox/03_timeout.py | defines its functions | main(), with members, wait_until_empty, group_escalation() and default_group() |
| Write transfer and the blocked write | sandbox/07_write_cost.py | defines its functions | main(), with the SINK and BODY constants printed with it |
| Three drain strategies | sandbox/07_write_cost.py | defines its functions | the same file’s main() |
| Pipe holders by inode and the grandchild case | sandbox/08_fd_inherit.py | defines its functions | main(), with PY and inode_of |
| Descriptor storm and the clean run | sandbox/05_asyncio_fd.py | defines the coroutines | run_probe() from the guard, with the census helpers and N printed with it |
| The stalled coroutine | sandbox/06_asyncio_read.py | defines the coroutine | run_probe() from the guard, which awaits main() with PY and CHILD |
| The stdin deadlock, old pattern | sandbox/10_stdin_deadlock.py | defines its functions | main(), with the NOT_READING and PAYLOAD constants printed with it |
procguard/pipe.py | module/procguard/pipe.py | defines its functions | imported from the package; standard library only |
procguard/group.py | module/procguard/group.py | defines its functions | imported from the package; standard library only |
procguard/run.py | module/procguard/run.py | imports its siblings, so only inside the package | run_captured, imported from procguard.run |
procguard/aio.py | module/procguard/aio.py | imports its siblings, so only inside the package | run_async, awaited from procguard.aio |
procguard/__init__.py | module/procguard/__init__.py | re-exports the public names | import procguard |
Test fixtures and helpers (conftest.py) | module/procguard/tests/conftest.py | defines fixtures and helpers | pytest, which loads it for every test module in that directory |
tests/test_regressions.py | module/procguard/tests/test_regressions.py | defines the tests | pytest, with conftest.py and the package on sys.path |
The PR_SET_PDEATHSIG spawner | sandbox/11_solutions.py | defines a string constant and its functions | main() passes the constant to -c |
What this article does not claim: the timing of any other kernel, page size or container runtime; cgroup or rlimit behaviour; systemd’s KillMode, which changes what a unit’s stop signal reaches; shells and pipelines; Windows job objects and handle inheritance; macOS; Python versions other than the one in Table 1; network sockets used as pipe substitutes; and any guarantee that a given init system reaps orphans. The zombie that persisted here with parent 1 is a property of this namespace’s PID 1 and would disappear on a host whose init reaps. The supervisor rows in Table 17 are the only claims taken from documentation rather than from a probe.
One limit is worth stating because it is easy to over-read: the throughput figures come from a child that discards its input and from a child that writes a repeated byte, so they measure the pipe and the reader’s loop rather than the cost of producing the bytes. A child whose output takes real work to compute will move at its own rate and the pipe will not be the bottleneck; the deadlock, the zombie and the orphan behaviour are unaffected by that and hold either way. The second limit is the host itself: the same 64 MiB transfer ran between 194.8 and 756.3 MiB/s across seven consecutive runs in section 14, with the parent’s CPU time moving in step, so a byte rate from this article is evidence about the shape of a failure rather than a benchmark for another machine or another hour. Why that spread exists was not established: steal time was not measured, so “another tenant on the same host” is the plausible reading of the correlation, not a finding.
20. Keep reading on TechBobby
This runbook is the process-level companion to the series on costs a request timer hides. The closest neighbours are about what runs inside the child and what holds the parent: ProcessPoolExecutor in production, where a forked worker inherits exactly the descriptors section 12 measured, and FastAPI on Gunicorn and UvicornWorker, where the worker’s own lifecycle decides how many processes share a supervisor.
For the stack around it: streaming in FastAPI and Starlette for the response side of the same buffer arithmetic, httpx AsyncClient in production for the other client that hangs on a deadline, memory leaks in production Python for what a leaked child turns into, pytest-asyncio in CI for the tests that should be catching this, Celery production architecture for the tasks that spawn the workers, Kubernetes pod resources and OOMKilled for the pid limit a zombie leak reaches, Docker multi-stage builds for Python for the image that runs them, and the asyncio scraping guide for the fan-out that spawns them in the first place. The TechBobby Stack is the tooling map these runbooks belong to.
Two free resources from TechBobby: the AI Prompt Pack for engineers and the Zero-Crash Python newsletter – free, one production failure per issue.
