use std::io;
use std::os::fd::{AsFd as _, AsRawFd as _, BorrowedFd, FromRawFd as _, OwnedFd};
use std::process::{Child, ExitStatus};
use std::time::{Duration, Instant};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Wakeup {
Exited(ExitStatus),
Woken,
Deadline,
}
const FALLBACK_SLICE: Duration = Duration::from_millis(10);
pub fn wait_child_or(
child: &mut Child,
wake: Option<BorrowedFd<'_>>,
deadline: Option<Instant>,
) -> io::Result<Wakeup> {
if let Some(status) = child.try_wait()? {
return Ok(Wakeup::Exited(status));
}
match pidfd(child) {
Some(pidfd) => wait_pidfd(child, &pidfd, wake, deadline),
None => wait_fallback(child, wake, deadline),
}
}
#[cfg(target_os = "linux")]
fn pidfd(child: &Child) -> Option<OwnedFd> {
let pid = libc::pid_t::try_from(child.id()).ok()?;
let fd = unsafe { libc::syscall(libc::SYS_pidfd_open, pid, 0) };
let fd = i32::try_from(fd).ok().filter(|fd| *fd >= 0)?;
Some(unsafe { OwnedFd::from_raw_fd(fd) })
}
#[cfg(not(target_os = "linux"))]
fn pidfd(_: &Child) -> Option<OwnedFd> {
None
}
fn wait_pidfd(
child: &mut Child,
pidfd: &OwnedFd,
wake: Option<BorrowedFd<'_>>,
deadline: Option<Instant>,
) -> io::Result<Wakeup> {
loop {
let mut fds = [
pollin(pidfd.as_raw_fd()),
pollin(wake.map_or(-1, |fd| fd.as_raw_fd())),
];
poll(&mut fds, remaining(deadline))?;
let [exited, woken] = fds;
if exited.revents != 0 {
return child.wait().map(Wakeup::Exited);
}
if woken.revents != 0 {
return Ok(Wakeup::Woken);
}
if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
return Ok(Wakeup::Deadline);
}
}
}
fn wait_fallback(
child: &mut Child,
wake: Option<BorrowedFd<'_>>,
deadline: Option<Instant>,
) -> io::Result<Wakeup> {
loop {
let slice = deadline.map_or(FALLBACK_SLICE, |deadline| {
deadline
.saturating_duration_since(Instant::now())
.min(FALLBACK_SLICE)
});
let mut fds = [pollin(wake.map_or(-1, |fd| fd.as_raw_fd()))];
poll(&mut fds, Some(slice))?;
if let Some(status) = child.try_wait()? {
return Ok(Wakeup::Exited(status));
}
if fds.iter().any(|fd| fd.revents != 0) {
return Ok(Wakeup::Woken);
}
if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
return Ok(Wakeup::Deadline);
}
}
}
fn pollin(fd: i32) -> libc::pollfd {
libc::pollfd {
fd,
events: libc::POLLIN,
revents: 0,
}
}
fn remaining(deadline: Option<Instant>) -> Option<Duration> {
deadline.map(|deadline| deadline.saturating_duration_since(Instant::now()))
}
fn poll(fds: &mut [libc::pollfd], timeout: Option<Duration>) -> io::Result<()> {
let count = libc::nfds_t::try_from(fds.len()).map_err(io::Error::other)?;
let started = Instant::now();
loop {
let remaining = timeout.map(|timeout| timeout.saturating_sub(started.elapsed()));
let millis = remaining.map_or(-1, |remaining| {
let micros = remaining.as_micros();
let millis = micros.div_ceil(1000);
i32::try_from(millis).unwrap_or(i32::MAX)
});
if unsafe { libc::poll(fds.as_mut_ptr(), count, millis) } >= 0 {
return Ok(());
}
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::Interrupted {
return Err(error);
}
}
}
#[derive(Debug)]
pub struct WakeFd {
read: OwnedFd,
#[cfg(not(target_os = "linux"))]
write: OwnedFd,
}
impl WakeFd {
#[cfg(target_os = "linux")]
pub fn new() -> io::Result<Self> {
let fd = unsafe { libc::eventfd(0, libc::EFD_CLOEXEC | libc::EFD_NONBLOCK) };
if fd < 0 {
return Err(io::Error::last_os_error());
}
Ok(Self {
read: unsafe { OwnedFd::from_raw_fd(fd) },
})
}
#[cfg(not(target_os = "linux"))]
pub fn new() -> io::Result<Self> {
let mut fds = [0; 2];
if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
return Err(io::Error::last_os_error());
}
let [read, write] = fds;
let (read, write) = unsafe { (OwnedFd::from_raw_fd(read), OwnedFd::from_raw_fd(write)) };
for fd in [&read, &write] {
let raw = fd.as_raw_fd();
if unsafe { libc::fcntl(raw, libc::F_SETFD, libc::FD_CLOEXEC) } != 0
|| unsafe { libc::fcntl(raw, libc::F_SETFL, libc::O_NONBLOCK) } != 0
{
return Err(io::Error::last_os_error());
}
}
Ok(Self { read, write })
}
pub fn ring(&self) {
let one = 1u64.to_ne_bytes();
unsafe {
libc::write(
self.ring_fd().as_raw_fd(),
one.as_ptr().cast(),
ring_len(one.len()),
)
};
}
pub fn fd(&self) -> BorrowedFd<'_> {
self.read.as_fd()
}
pub fn drain(&self) {
let mut buffer = [0u8; 64];
while unsafe {
libc::read(
self.read.as_raw_fd(),
buffer.as_mut_ptr().cast(),
buffer.len(),
)
} > 0
{}
}
#[cfg(target_os = "linux")]
fn ring_fd(&self) -> BorrowedFd<'_> {
self.read.as_fd()
}
#[cfg(not(target_os = "linux"))]
fn ring_fd(&self) -> BorrowedFd<'_> {
self.write.as_fd()
}
}
#[cfg(target_os = "linux")]
fn ring_len(len: usize) -> usize {
len
}
#[cfg(not(target_os = "linux"))]
fn ring_len(_: usize) -> usize {
1
}
#[cfg(test)]
mod tests {
use super::*;
use std::process::Command;
use tilo_test_env::SpawnUnderEnvLock as _;
fn sleeper(seconds: &str) -> Child {
Command::new("sleep").arg(seconds).spawn_locked().unwrap()
}
#[cfg(target_os = "linux")]
fn context_switches() -> u64 {
let tid = tilo_test_env::idle::current_thread_id().unwrap();
tilo_test_env::idle::context_switches(&tid.to_string())
}
#[test]
#[cfg(target_os = "linux")]
fn wait_child_or_returns_on_exit_without_polling() {
let mut child = sleeper("0.2");
let before = context_switches();
let began = Instant::now();
let woke = wait_child_or(&mut child, None, None).unwrap();
let switches = context_switches().saturating_sub(before);
assert!(matches!(woke, Wakeup::Exited(status) if status.success()));
assert!(began.elapsed() >= Duration::from_millis(150));
assert!(
switches <= 3,
"waiting 200 ms for exit took {switches} context switches"
);
}
tilo_test_env::scenario! {
fn wait_child_or_returns_on_a_wake_or_a_deadline;
phase wait_child_or_returns_on_wake;
{
let mut child = sleeper("3600");
let wake = std::sync::Arc::new(WakeFd::new().unwrap());
let ringer = wake.clone();
let thread = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(50));
ringer.ring();
});
let first = wait_child_or(&mut child, Some(wake.fd()), None).unwrap();
thread.join().unwrap();
assert_eq!(first, Wakeup::Woken);
let soon = Instant::now()
.checked_add(Duration::from_millis(30))
.unwrap();
assert_eq!(
wait_child_or(&mut child, Some(wake.fd()), Some(soon)).unwrap(),
Wakeup::Woken
);
wake.drain();
let soon = Instant::now()
.checked_add(Duration::from_millis(30))
.unwrap();
assert_eq!(
wait_child_or(&mut child, Some(wake.fd()), Some(soon)).unwrap(),
Wakeup::Deadline
);
child.kill().unwrap();
assert!(matches!(
wait_child_or(&mut child, Some(wake.fd()), None).unwrap(),
Wakeup::Exited(_)
));
}
phase wait_child_or_honours_deadline;
{
let mut child = sleeper("3600");
let began = Instant::now();
let deadline = began.checked_add(Duration::from_millis(100)).unwrap();
assert_eq!(
wait_child_or(&mut child, None, Some(deadline)).unwrap(),
Wakeup::Deadline
);
assert!(Instant::now() >= deadline);
assert_eq!(
wait_child_or(&mut child, None, Some(began)).unwrap(),
Wakeup::Deadline
);
child.kill().unwrap();
child.wait().unwrap();
assert!(matches!(
wait_child_or(&mut child, None, Some(began)).unwrap(),
Wakeup::Exited(_)
));
}
}
}