Skip to main content

bounded_command/
child_wait.rs

1//! Supervise a child without waking up while nothing happens.
2//!
3//! A supervisor that learns of exit or cancellation by calling `Child::try_wait` on
4//! a timer is scheduled on every tick for the child's whole life. On Linux a pidfd
5//! becomes readable when its process exits, so a supervisor can sleep in one
6//! `poll(2)` on that pidfd and a [`WakeFd`] that any thread or signal handler rings,
7//! and wake only for an event.
8
9use std::io;
10use std::os::fd::{AsFd as _, AsRawFd as _, BorrowedFd, FromRawFd as _, OwnedFd};
11use std::process::{Child, ExitStatus};
12use std::time::{Duration, Instant};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Wakeup {
16    Exited(ExitStatus),
17    Woken,
18    Deadline,
19}
20
21/// Slice of the portable fallback, for kernels without `pidfd_open` and
22/// non-Linux hosts: the supervision loop this module replaces.
23const FALLBACK_SLICE: Duration = Duration::from_millis(10);
24
25/// Wait until `child` exits, `wake` becomes readable, or `deadline` passes, without
26/// polling. With neither a wake descriptor nor a deadline this blocks until the
27/// child exits; a deadline already in the past only probes.
28///
29/// Linux: one `poll(2)` on a pidfd of `child` (pinned to this unreaped child, so it
30/// cannot name a recycled pid) and `wake`. Elsewhere, or without `pidfd_open`, a
31/// short `try_wait` loop keeps the same contract.
32///
33/// # Errors
34/// Returns the error of inspecting or reaping the child, or of `poll(2)`.
35pub fn wait_child_or(
36    child: &mut Child,
37    wake: Option<BorrowedFd<'_>>,
38    deadline: Option<Instant>,
39) -> io::Result<Wakeup> {
40    if let Some(status) = child.try_wait()? {
41        return Ok(Wakeup::Exited(status));
42    }
43    match pidfd(child) {
44        Some(pidfd) => wait_pidfd(child, &pidfd, wake, deadline),
45        None => wait_fallback(child, wake, deadline),
46    }
47}
48
49#[cfg(target_os = "linux")]
50fn pidfd(child: &Child) -> Option<OwnedFd> {
51    let pid = libc::pid_t::try_from(child.id()).ok()?;
52    // SAFETY: pidfd_open takes a pid and flags and returns a new descriptor
53    // or -1. The child is unreaped, so its pid still names exactly it.
54    let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
55    let fd = i32::try_from(fd).ok().filter(|fd| *fd >= 0)?;
56    // SAFETY: the kernel returned a fresh descriptor this call now owns.
57    Some(unsafe { OwnedFd::from_raw_fd(fd) })
58}
59
60#[cfg(not(target_os = "linux"))]
61fn pidfd(_: &Child) -> Option<OwnedFd> {
62    None
63}
64
65fn wait_pidfd(
66    child: &mut Child,
67    pidfd: &OwnedFd,
68    wake: Option<BorrowedFd<'_>>,
69    deadline: Option<Instant>,
70) -> io::Result<Wakeup> {
71    loop {
72        let mut fds = [
73            pollin(pidfd.as_raw_fd()),
74            // poll(2) ignores a negative descriptor.
75            pollin(wake.map_or(-1, |fd| fd.as_raw_fd())),
76        ];
77        poll(&mut fds, remaining(deadline))?;
78        let [exited, woken] = fds;
79        if exited.revents != 0 {
80            return child.wait().map(Wakeup::Exited);
81        }
82        if woken.revents != 0 {
83            return Ok(Wakeup::Woken);
84        }
85        if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
86            return Ok(Wakeup::Deadline);
87        }
88    }
89}
90
91fn wait_fallback(
92    child: &mut Child,
93    wake: Option<BorrowedFd<'_>>,
94    deadline: Option<Instant>,
95) -> io::Result<Wakeup> {
96    loop {
97        let slice = deadline.map_or(FALLBACK_SLICE, |deadline| {
98            deadline
99                .saturating_duration_since(Instant::now())
100                .min(FALLBACK_SLICE)
101        });
102        let mut fds = [pollin(wake.map_or(-1, |fd| fd.as_raw_fd()))];
103        poll(&mut fds, Some(slice))?;
104        if let Some(status) = child.try_wait()? {
105            return Ok(Wakeup::Exited(status));
106        }
107        if fds.iter().any(|fd| fd.revents != 0) {
108            return Ok(Wakeup::Woken);
109        }
110        if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
111            return Ok(Wakeup::Deadline);
112        }
113    }
114}
115
116fn pollin(fd: i32) -> libc::pollfd {
117    libc::pollfd {
118        fd,
119        events: libc::POLLIN,
120        revents: 0,
121    }
122}
123
124fn remaining(deadline: Option<Instant>) -> Option<Duration> {
125    deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()))
126}
127
128/// `poll(2)` that retries an interrupted call (the caller recomputes nothing:
129/// a signal that matters rings a wake descriptor, which the retry observes).
130fn poll(fds: &mut [libc::pollfd], timeout: Option<Duration>) -> io::Result<()> {
131    let count = libc::nfds_t::try_from(fds.len()).map_err(io::Error::other)?;
132    let started = Instant::now();
133    loop {
134        let remaining = timeout.map(|timeout| timeout.saturating_sub(started.elapsed()));
135        // Round up, so a timed-out poll means the deadline really passed.
136        let millis = remaining.map_or(-1, |remaining| {
137            let micros = remaining.as_micros();
138            let millis = micros.div_ceil(1000);
139            i32::try_from(millis).unwrap_or(i32::MAX)
140        });
141        // SAFETY: `fds` is a valid, exclusively borrowed array of `count`
142        // pollfd entries for the duration of the call.
143        if unsafe { libc::poll(fds.as_mut_ptr(), count, millis) } >= 0 {
144            return Ok(());
145        }
146        let error = io::Error::last_os_error();
147        if error.kind() != io::ErrorKind::Interrupted {
148            return Err(error);
149        }
150    }
151}
152
153/// A level-triggered wake descriptor: readable from the first [`ring`] until
154/// [`drain`]. A supervisor passes [`fd`] to [`wait_child_or`]; any thread rings it
155/// after changing what the supervisor must re-check.
156///
157/// [`ring`]: WakeFd::ring
158/// [`drain`]: WakeFd::drain
159/// [`fd`]: WakeFd::fd
160#[derive(Debug)]
161pub struct WakeFd {
162    read: OwnedFd,
163    /// The pipe's write end; an eventfd reads and writes one descriptor.
164    #[cfg(not(target_os = "linux"))]
165    write: OwnedFd,
166}
167
168impl WakeFd {
169    #[cfg(target_os = "linux")]
170    pub fn new() -> io::Result<Self> {
171        // SAFETY: eventfd takes an initial count and flags and returns a new
172        // descriptor or -1.
173        let fd = unsafe { libc::eventfd(0, libc::EFD_CLOEXEC | libc::EFD_NONBLOCK) };
174        if fd < 0 {
175            return Err(io::Error::last_os_error());
176        }
177        // SAFETY: the kernel returned a fresh descriptor this call now owns.
178        Ok(Self {
179            read: unsafe { OwnedFd::from_raw_fd(fd) },
180        })
181    }
182
183    #[cfg(not(target_os = "linux"))]
184    pub fn new() -> io::Result<Self> {
185        let mut fds = [0; 2];
186        // SAFETY: pipe writes two new descriptors into the two-element array.
187        if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
188            return Err(io::Error::last_os_error());
189        }
190        let [read, write] = fds;
191        // SAFETY: pipe returned two fresh descriptors this call now owns.
192        let (read, write) = unsafe { (OwnedFd::from_raw_fd(read), OwnedFd::from_raw_fd(write)) };
193        for fd in [&read, &write] {
194            let raw = fd.as_raw_fd();
195            // SAFETY: fcntl only changes flags of a descriptor owned above.
196            if unsafe { libc::fcntl(raw, libc::F_SETFD, libc::FD_CLOEXEC) } != 0
197                || unsafe { libc::fcntl(raw, libc::F_SETFL, libc::O_NONBLOCK) } != 0
198            {
199                return Err(io::Error::last_os_error());
200            }
201        }
202        Ok(Self { read, write })
203    }
204
205    /// Make the descriptor readable. Only a `write(2)`: no allocation or lock,
206    /// so a signal handler may call it. A full counter or pipe is already
207    /// readable, so a failed write loses nothing.
208    pub fn ring(&self) {
209        let one = 1u64.to_ne_bytes();
210        // SAFETY: writes from a valid local buffer to a descriptor owned by
211        // this value; the result is deliberately ignored (see above).
212        unsafe {
213            libc::write(
214                self.ring_fd().as_raw_fd(),
215                one.as_ptr().cast(),
216                ring_len(one.len()),
217            )
218        };
219    }
220
221    /// The descriptor to wait on; readable while rung and not drained.
222    pub fn fd(&self) -> BorrowedFd<'_> {
223        self.read.as_fd()
224    }
225
226    /// Consume every ring so far, making the descriptor unreadable again.
227    /// Drain before re-checking state, so a ring racing the check is kept.
228    pub fn drain(&self) {
229        let mut buffer = [0u8; 64];
230        // SAFETY: reads into a valid local buffer from a nonblocking
231        // descriptor owned by this value; stops at EAGAIN or end.
232        while unsafe {
233            libc::read(
234                self.read.as_raw_fd(),
235                buffer.as_mut_ptr().cast(),
236                buffer.len(),
237            )
238        } > 0
239        {}
240    }
241
242    #[cfg(target_os = "linux")]
243    fn ring_fd(&self) -> BorrowedFd<'_> {
244        self.read.as_fd()
245    }
246
247    #[cfg(not(target_os = "linux"))]
248    fn ring_fd(&self) -> BorrowedFd<'_> {
249        self.write.as_fd()
250    }
251}
252
253#[cfg(target_os = "linux")]
254fn ring_len(len: usize) -> usize {
255    len
256}
257
258#[cfg(not(target_os = "linux"))]
259fn ring_len(_: usize) -> usize {
260    1
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use std::process::Command;
267    use tilo_test_env::SpawnUnderEnvLock as _;
268
269    fn sleeper(seconds: &str) -> Child {
270        Command::new("sleep").arg(seconds).spawn_locked().unwrap()
271    }
272
273    #[cfg(target_os = "linux")]
274    fn context_switches() -> u64 {
275        let tid = tilo_test_env::idle::current_thread_id().unwrap();
276        tilo_test_env::idle::context_switches(&tid.to_string())
277    }
278
279    #[test]
280    #[cfg(target_os = "linux")]
281    fn wait_child_or_returns_on_exit_without_polling() {
282        let mut child = sleeper("0.2");
283        let before = context_switches();
284        let began = Instant::now();
285        let woke = wait_child_or(&mut child, None, None).unwrap();
286        let switches = context_switches().saturating_sub(before);
287        assert!(matches!(woke, Wakeup::Exited(status) if status.success()));
288        assert!(began.elapsed() >= Duration::from_millis(150));
289        // The 10 ms loop this replaces switched about 20 times here.
290        assert!(
291            switches <= 3,
292            "waiting 200 ms for exit took {switches} context switches"
293        );
294    }
295
296    tilo_test_env::scenario! {
297        /// `wait_child_or`, where the wait is not measured in context switches.
298        fn wait_child_or_returns_on_a_wake_or_a_deadline;
299
300        phase wait_child_or_returns_on_wake;
301        {
302            let mut child = sleeper("3600");
303            let wake = std::sync::Arc::new(WakeFd::new().unwrap());
304            let ringer = wake.clone();
305            let thread = std::thread::spawn(move || {
306                std::thread::sleep(Duration::from_millis(50));
307                ringer.ring();
308            });
309            let first = wait_child_or(&mut child, Some(wake.fd()), None).unwrap();
310            thread.join().unwrap();
311            assert_eq!(first, Wakeup::Woken);
312            // Level-triggered until drained, then quiet again.
313            let soon = Instant::now()
314                .checked_add(Duration::from_millis(30))
315                .unwrap();
316            assert_eq!(
317                wait_child_or(&mut child, Some(wake.fd()), Some(soon)).unwrap(),
318                Wakeup::Woken
319            );
320            wake.drain();
321            let soon = Instant::now()
322                .checked_add(Duration::from_millis(30))
323                .unwrap();
324            assert_eq!(
325                wait_child_or(&mut child, Some(wake.fd()), Some(soon)).unwrap(),
326                Wakeup::Deadline
327            );
328            child.kill().unwrap();
329            assert!(matches!(
330                wait_child_or(&mut child, Some(wake.fd()), None).unwrap(),
331                Wakeup::Exited(_)
332            ));
333        }
334
335        phase wait_child_or_honours_deadline;
336        {
337            let mut child = sleeper("3600");
338            let began = Instant::now();
339            let deadline = began.checked_add(Duration::from_millis(100)).unwrap();
340            assert_eq!(
341                wait_child_or(&mut child, None, Some(deadline)).unwrap(),
342                Wakeup::Deadline
343            );
344            assert!(Instant::now() >= deadline);
345            // A past deadline only probes a live child.
346            assert_eq!(
347                wait_child_or(&mut child, None, Some(began)).unwrap(),
348                Wakeup::Deadline
349            );
350            child.kill().unwrap();
351            child.wait().unwrap();
352            assert!(matches!(
353                wait_child_or(&mut child, None, Some(began)).unwrap(),
354                Wakeup::Exited(_)
355            ));
356        }
357    }
358}