Debian Codegraph @

src/trio/_subprocess_platform/waitid.py

raw
1 import errno
2 import math
3 import os
4 import sys
5 from typing import TYPE_CHECKING
6
7 from .. import _core, _subprocess
8 from .._sync import CapacityLimiter, Event
9 from .._threads import to_thread_run_sync
10
11 assert (sys.platform != "win32" and sys.platform != "darwin") or not TYPE_CHECKING
12
13 try:
14 from os import waitid
15
16 def sync_wait_reapable(pid: int) -> None:
17 waitid(os.P_PID, pid, os.WEXITED | os.WNOWAIT)
18
19 except ImportError:
20 # pypy doesn't define os.waitid so we need to pull it out ourselves
21 # using cffi: https://bitbucket.org/pypy/pypy/issues/2922/
22 import cffi
23
24 waitid_ffi = cffi.FFI()
25
26 # Believe it or not, siginfo_t starts with fields in the
27 # same layout on both Linux and Darwin. The Linux structure
28 # is bigger so that's what we use to size `pad`; while
29 # there are a few extra fields in there, most of it is
30 # true padding which would not be written by the syscall.
31 waitid_ffi.cdef(
32 """
33 typedef struct siginfo_s {
34 int si_signo;
35 int si_errno;
36 int si_code;
37 int si_pid;
38 int si_uid;
39 int si_status;
40 int pad[26];
41 } siginfo_t;
42 int waitid(int idtype, int id, siginfo_t* result, int options);
43 """,
44 )
45 waitid_cffi = waitid_ffi.dlopen(None).waitid # type: ignore[attr-defined]
46
47 def sync_wait_reapable(pid: int) -> None:
48 P_PID = 1
49 WEXITED = 0x00000004
50 if sys.platform == "darwin": # pragma: no cover
51 # waitid() is not exposed on Python on Darwin but does
52 # work through CFFI; note that we typically won't get
53 # here since Darwin also defines kqueue
54 WNOWAIT = 0x00000020
55 else:
56 WNOWAIT = 0x01000000
57 result = waitid_ffi.new("siginfo_t *")
58 while waitid_cffi(P_PID, pid, result, WEXITED | WNOWAIT) < 0:
59 got_errno = waitid_ffi.errno
60 if got_errno == errno.EINTR:
61 continue
62 raise OSError(got_errno, os.strerror(got_errno))
63
64
65 # adapted from
66 # https://github.com/python-trio/trio/issues/4#issuecomment-398967572
67
68 waitid_limiter = CapacityLimiter(math.inf)
69
70
71 async def _waitid_system_task(pid: int, event: Event) -> None:
72 """Spawn a thread that waits for ``pid`` to exit, then wake any tasks
73 that were waiting on it.
74 """
75 # abandon_on_cancel=True: if this task is cancelled, then we abandon the
76 # thread to keep running waitpid in the background. Since this is
77 # always run as a system task, this will only happen if the whole
78 # call to trio.run is shutting down.
79
80 try:
81 await to_thread_run_sync(
82 sync_wait_reapable,
83 pid,
84 abandon_on_cancel=True,
85 limiter=waitid_limiter,
86 )
87 except OSError:
88 # If waitid fails, waitpid will fail too, so it still makes
89 # sense to wake up the callers of wait_process_exiting(). The
90 # most likely reason for this error in practice is a child
91 # exiting when wait() is not possible because SIGCHLD is
92 # ignored.
93 pass
94 finally:
95 event.set()
96
97
98 async def wait_child_exiting(process: "_subprocess.Process") -> None:
99 # Logic of this function:
100 # - The first time we get called, we create an Event and start
101 # an instance of _waitid_system_task that will set the Event
102 # when waitid() completes. If that Event is set before
103 # we get cancelled, we're good.
104 # - Otherwise, a following call after the cancellation must
105 # reuse the Event created during the first call, lest we
106 # create an arbitrary number of threads waiting on the same
107 # process.
108
109 if process._wait_for_exit_data is None:
110 process._wait_for_exit_data = event = Event()
111 _core.spawn_system_task(_waitid_system_task, process.pid, event)
112 assert isinstance(process._wait_for_exit_data, Event)
113 await process._wait_for_exit_data.wait()