1use std::process::Child;
10use std::time::Duration;
11
12const FALLBACK_PAUSE: Duration = Duration::from_millis(100);
13
14pub struct ExitWatch(backend::Watch);
16
17#[derive(Clone)]
18pub struct Bell(backend::Bell);
19
20impl ExitWatch {
21 #[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 pub fn wait(&self, deadline: Option<Duration>) {
33 self.0.wait(deadline);
34 }
35
36 #[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 let raw = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
76 let fd = i32::try_from(raw).ok().filter(|fd| *fd >= 0)?;
77 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 let _ = unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout) };
124 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 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 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}