`test_managed_worker_launch` failed on a PR run with `psutil.ZombieProcess` from `[p for p in owner.children() if p.cmdline() ...]`: the list is taken first, then each child's cmdline is read, and a short-lived sibling of the worker that exited in between raises for a process the test never cared about. Four more tests scan children the same way. `tests/process_scan.py::children_matching` / `matching` skip a process that exits mid-read (it cannot be the one being looked for); every such scan uses it. Repro: with an unreaped child of the scanning process, the old comprehension raises ZombieProcess and the helper finds the live target.
33 lines
1.3 KiB
Python
33 lines
1.3 KiB
Python
"""Find a process's children by their command line without racing their exit.
|
|
|
|
``[p for p in proc.children() if p.cmdline() ...]`` reads each child's ``/proc`` entry after the
|
|
list was taken: a short-lived sibling that exits in between is a zombie or gone, and ``cmdline()``
|
|
raises ``ZombieProcess`` / ``NoSuchProcess`` for a process the test never cared about. Such a
|
|
child cannot be the one being looked for, so it is skipped.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from collections.abc import Callable, Iterable
|
|
|
|
import psutil
|
|
|
|
|
|
def matching(procs: Iterable[psutil.Process], predicate: Callable[[psutil.Process], bool]) -> list[psutil.Process]:
|
|
"""The live processes in *procs* that *predicate* accepts; one that exits mid-read is skipped."""
|
|
found = []
|
|
for proc in procs:
|
|
try:
|
|
if predicate(proc):
|
|
found.append(proc)
|
|
except (psutil.NoSuchProcess, psutil.AccessDenied): # ZombieProcess is a NoSuchProcess
|
|
continue
|
|
return found
|
|
|
|
|
|
def children_matching(pid: int | psutil.Process, predicate: Callable[[psutil.Process], bool], *,
|
|
recursive: bool = False) -> list[psutil.Process]:
|
|
"""``matching`` over the children of *pid*."""
|
|
proc = pid if isinstance(pid, psutil.Process) else psutil.Process(pid)
|
|
return matching(proc.children(recursive=recursive), predicate)
|