1use 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
21const FALLBACK_SLICE: Duration = Duration::from_millis(10);
24
25pub 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 let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
55 let fd = i32::try_from(fd).ok().filter(|fd| *fd >= 0)?;
56 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 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
128fn 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 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 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#[derive(Debug)]
161pub struct WakeFd {
162 read: OwnedFd,
163 #[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 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 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 if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
188 return Err(io::Error::last_os_error());
189 }
190 let [read, write] = fds;
191 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 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 pub fn ring(&self) {
209 let one = 1u64.to_ne_bytes();
210 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 pub fn fd(&self) -> BorrowedFd<'_> {
223 self.read.as_fd()
224 }
225
226 pub fn drain(&self) {
229 let mut buffer = [0u8; 64];
230 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 assert!(
291 switches <= 3,
292 "waiting 200 ms for exit took {switches} context switches"
293 );
294 }
295
296 tilo_test_env::scenario! {
297 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 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 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}