Skip to main content

tilo_process/
child.rs

1//! Waiting on a child process without polling it.
2//!
3//! An [`ExitWatch`] sleeps until the child exits or its [`Bell`] rings, so a
4//! supervisor reacts to other events without looking at the child on a timer.
5//! On Linux it waits on a pidfd, which becomes readable when the child exits
6//! without reaping it; where no such handle exists, [`ExitWatch::wait`] returns
7//! after at most 100 ms.
8
9use std::process::Child;
10use std::time::Duration;
11
12const FALLBACK_PAUSE: Duration = Duration::from_millis(100);
13
14/// Sleeps until a child exits, its [`Bell`] rings or a deadline passes.
15pub struct ExitWatch(backend::Watch);
16
17#[derive(Clone)]
18pub struct Bell(backend::Bell);
19
20impl ExitWatch {
21    /// Watches `child`, and returns the bell that wakes [`Self::wait`]. `child` must
22    /// not have been waited for yet: once reaped, its process id can name another
23    /// process.
24    #[must_use]
25    pub fn new(child: &Child) -> (Self, Bell) {
26        let (watch, bell) = backend::watch(child);
27        (Self(watch), Bell(bell))
28    }
29
30    /// Sleeps until the child exits, the bell rings or `deadline` (from now) passes;
31    /// `None` waits without a deadline. It never reaps the child.
32    pub fn wait(&self, deadline: Option<Duration>) {
33        self.0.wait(deadline);
34    }
35
36    /// Whether the system lets this watch sleep until the child exits, rather
37    /// than returning every 100 ms.
38    #[must_use]
39    pub fn watches_the_process(&self) -> bool {
40        self.0.watches_the_process()
41    }
42}
43
44impl Bell {
45    pub fn ring(&self) {
46        self.0.ring();
47    }
48}
49
50fn fallback_pause(deadline: Option<Duration>) -> Duration {
51    deadline.map_or(FALLBACK_PAUSE, |left| left.min(FALLBACK_PAUSE))
52}
53
54#[cfg(target_os = "linux")]
55mod backend {
56    use std::io::{Read, Write};
57    use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
58    use std::os::unix::net::UnixStream;
59    use std::process::Child;
60    use std::sync::Arc;
61    use std::time::Duration;
62
63    pub struct Watch {
64        fds: Option<(OwnedFd, UnixStream)>,
65    }
66
67    #[derive(Clone)]
68    pub struct Bell(Option<Arc<UnixStream>>);
69
70    fn pidfd(child: &Child) -> Option<OwnedFd> {
71        let pid = libc::pid_t::try_from(child.id()).ok()?;
72        // SAFETY: pidfd_open takes a pid and flags and returns a new
73        // descriptor or -1. The caller has not reaped the child, so the pid
74        // still names it.
75        let raw = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
76        let fd = i32::try_from(raw).ok().filter(|fd| *fd >= 0)?;
77        // SAFETY: pidfd_open returned a new descriptor nothing else owns.
78        Some(unsafe { OwnedFd::from_raw_fd(fd) })
79    }
80
81    fn bell() -> std::io::Result<(UnixStream, UnixStream)> {
82        let (ring, listen) = UnixStream::pair()?;
83        ring.set_nonblocking(true)?;
84        listen.set_nonblocking(true)?;
85        Ok((ring, listen))
86    }
87
88    pub fn watch(child: &Child) -> (Watch, Bell) {
89        match (pidfd(child), bell()) {
90            (Some(pidfd), Ok((ring, listen))) => (
91                Watch {
92                    fds: Some((pidfd, listen)),
93                },
94                Bell(Some(Arc::new(ring))),
95            ),
96            _ => (Watch { fds: None }, Bell(None)),
97        }
98    }
99
100    impl Watch {
101        pub fn wait(&self, deadline: Option<Duration>) {
102            let Some((pidfd, listen)) = &self.fds else {
103                std::thread::sleep(super::fallback_pause(deadline));
104                return;
105            };
106            let mut fds = [
107                libc::pollfd {
108                    fd: pidfd.as_raw_fd(),
109                    events: libc::POLLIN,
110                    revents: 0,
111                },
112                libc::pollfd {
113                    fd: listen.as_raw_fd(),
114                    events: libc::POLLIN,
115                    revents: 0,
116                },
117            ];
118            let timeout = deadline.map_or(-1, |left| {
119                i32::try_from(left.as_millis().saturating_add(1)).unwrap_or(i32::MAX)
120            });
121            // SAFETY: two initialised pollfds over descriptors this watch
122            // owns; poll writes only their `revents`.
123            let _ = unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout) };
124            // Empty the bell: the caller looks at everything after a wait.
125            let mut drain = [0u8; 64];
126            while matches!((&*listen).read(&mut drain), Ok(n) if n > 0) {}
127        }
128
129        pub const fn watches_the_process(&self) -> bool {
130            self.fds.is_some()
131        }
132    }
133
134    impl Bell {
135        pub fn ring(&self) {
136            if let Some(ring) = &self.0 {
137                let _ = (&**ring).write(&[1]);
138            }
139        }
140    }
141}
142
143#[cfg(not(target_os = "linux"))]
144mod backend {
145    use std::process::Child;
146    use std::time::Duration;
147
148    pub struct Watch;
149
150    #[derive(Clone)]
151    pub struct Bell;
152
153    pub const fn watch(_child: &Child) -> (Watch, Bell) {
154        (Watch, Bell)
155    }
156
157    impl Watch {
158        #[allow(
159            clippy::unused_self,
160            reason = "the signature is shared with the Linux backend, which waits on its descriptors"
161        )]
162        pub fn wait(&self, deadline: Option<Duration>) {
163            std::thread::sleep(super::fallback_pause(deadline));
164        }
165
166        #[allow(
167            clippy::unused_self,
168            reason = "the signature is shared with the Linux backend, which has a process to watch"
169        )]
170        pub const fn watches_the_process(&self) -> bool {
171            false
172        }
173    }
174
175    impl Bell {
176        #[allow(
177            clippy::unused_self,
178            reason = "the signature is shared with the Linux backend, whose bell wakes a watch"
179        )]
180        pub const fn ring(&self) {}
181    }
182}
183
184#[cfg(all(test, unix))]
185mod tests {
186    use super::*;
187    use std::process::{Command, Stdio};
188    use std::time::Instant;
189    use tilo_test_env::SpawnUnderEnvLock as _;
190
191    #[allow(clippy::unwrap_used, reason = "a test helper fails loudly")]
192    fn sleeper(seconds: &str) -> Child {
193        Command::new("sleep")
194            .arg(seconds)
195            .stdin(Stdio::null())
196            .spawn_locked()
197            .unwrap()
198    }
199
200    /// Block on `watch` on its own thread, and fail as hung if nothing wakes
201    /// it within the shared hang bound.
202    fn woken(watch: ExitWatch, what: &str) {
203        let (woke, woken) = std::sync::mpsc::channel();
204        std::thread::spawn(move || {
205            watch.wait(None);
206            let _ = woke.send(());
207        });
208        tilo_test_env::recv(what, &woken);
209    }
210
211    tilo_test_env::scenario! {
212        fn the_exit_watch_sleeps_until_its_deadline_and_wakes_on_an_exit_or_a_ring;
213
214        phase a_running_child_keeps_the_watch_asleep_until_the_deadline;
215        {
216            let mut child = sleeper("5");
217            let (watch, _bell) = ExitWatch::new(&child);
218            assert_eq!(watch.watches_the_process(), cfg!(target_os = "linux"));
219            if watch.watches_the_process() {
220                let began = Instant::now();
221                watch.wait(Some(Duration::from_millis(400)));
222                assert!(began.elapsed() >= Duration::from_millis(400));
223            }
224            let _ = child.kill();
225            let _ = child.wait();
226        }
227
228        phase an_exit_or_a_ring_wakes_the_watch_at_once;
229        {
230            // The child outlives the test, so only the ring can wake the watch.
231            let mut child = sleeper("3600");
232            let (watch, bell) = ExitWatch::new(&child);
233            if !watch.watches_the_process() {
234                let _ = child.kill();
235                let _ = child.wait();
236                return;
237            }
238            bell.ring();
239            woken(watch, "the ring to wake the watch");
240
241            let mut quick = sleeper("0");
242            let (watch, _bell) = ExitWatch::new(&quick);
243            woken(watch, "the exit to wake the watch");
244            assert!(quick.wait().unwrap().success());
245            let _ = child.kill();
246            let _ = child.wait();
247        }
248    }
249}