Debian Codegraph @

src/trio/_subprocess_platform/kqueue.py

raw
1 from __future__ import annotations
2
3 import select
4 import sys
5 from typing import TYPE_CHECKING
6
7 from .. import _core, _subprocess
8
9 assert (sys.platform != "win32" and sys.platform != "linux") or not TYPE_CHECKING
10
11
12 async def wait_child_exiting(process: _subprocess.Process) -> None:
13 kqueue = _core.current_kqueue()
14 try:
15 from select import KQ_NOTE_EXIT
16 except ImportError: # pragma: no cover
17 # pypy doesn't define KQ_NOTE_EXIT:
18 # https://bitbucket.org/pypy/pypy/issues/2921/
19 # I verified this value against both Darwin and FreeBSD
20 KQ_NOTE_EXIT = 0x80000000 # type: ignore[misc]
21
22 def make_event(flags: int) -> select.kevent:
23 return select.kevent(
24 process.pid,
25 filter=select.KQ_FILTER_PROC,
26 flags=flags,
27 fflags=KQ_NOTE_EXIT,
28 )
29
30 try:
31 kqueue.control([make_event(select.KQ_EV_ADD | select.KQ_EV_ONESHOT)], 0)
32 except ProcessLookupError: # pragma: no cover
33 # This can supposedly happen if the process is in the process
34 # of exiting, and it can even be the case that kqueue says the
35 # process doesn't exist before waitpid(WNOHANG) says it hasn't
36 # exited yet. See the discussion in https://chromium.googlesource.com/
37 # chromium/src/base/+/master/process/kill_mac.cc .
38 # We haven't actually seen this error occur since we added
39 # locking to prevent multiple calls to wait_child_exiting()
40 # for the same process simultaneously, but given the explanation
41 # in Chromium it seems we should still keep the check.
42 return
43
44 def abort(_: _core.RaiseCancelT) -> _core.Abort:
45 kqueue.control([make_event(select.KQ_EV_DELETE)], 0)
46 return _core.Abort.SUCCEEDED
47
48 await _core.wait_kevent(process.pid, select.KQ_FILTER_PROC, abort)