use std::time::Duration;
use crate::error::Error;
use crate::identity::ProcessId;
#[cfg(unix)]
pub(crate) async fn wait_exit(id: ProcessId) -> Result<(), Error> {
#[cfg(test)]
if crate::wait::fault::take_force_watch_error() {
return Err(crate::wait::fault::forced_watch_error());
}
exit_watch(id).await
}
#[cfg(unix)]
pub(crate) async fn grace_wait(id: ProcessId, grace: Duration) -> Result<bool, Error> {
if grace.is_zero() {
return crate::wait::block_until_exit(id, Some(Duration::ZERO));
}
match ::tokio::time::timeout(grace, wait_exit(id)).await {
Ok(watch) => watch.map(|()| true),
Err(_elapsed) => Ok(false),
}
}
#[cfg(windows)]
async fn blocking_watch(id: ProcessId, grace: Option<Duration>) -> Result<bool, Error> {
struct SignalOnDrop(std::sync::Arc<std::os::windows::io::OwnedHandle>);
impl Drop for SignalOnDrop {
fn drop(&mut self) {
crate::wait::backend::signal_cancel(&self.0);
}
}
let cancel = std::sync::Arc::new(crate::wait::backend::new_cancel_event()?);
let _guard = SignalOnDrop(cancel.clone());
let joined = ::tokio::task::spawn_blocking(move || {
let result = crate::wait::backend::block_until_exit_or_cancel(id, grace, &cancel);
#[cfg(test)]
fault_observer::notify_released();
result
})
.await;
match joined {
Ok(result) => result,
Err(e) if e.is_panic() => std::panic::resume_unwind(e.into_panic()),
Err(e) if e.is_cancelled() => Err(Error::Io(std::io::Error::other(
"grace-wait watcher cancelled (runtime shutting down)",
))),
Err(e) => {
debug_assert!(false, "unknown JoinError variant: {e:?}");
Err(Error::Io(std::io::Error::other(e)))
}
}
}
#[cfg(windows)]
pub(crate) async fn grace_wait(id: ProcessId, grace: Duration) -> Result<bool, Error> {
#[cfg(test)]
if crate::wait::fault::take_force_watch_error() {
return Err(crate::wait::fault::forced_watch_error());
}
blocking_watch(id, Some(grace)).await
}
#[cfg(windows)]
pub(crate) async fn wait_exit(id: ProcessId) -> Result<(), Error> {
#[cfg(test)]
if crate::wait::fault::take_force_watch_error() {
return Err(crate::wait::fault::forced_watch_error());
}
loop {
let exited = blocking_watch(id, None).await?;
debug_assert!(exited, "an unbounded watch resolved without an exit");
if exited {
return Ok(());
}
log::warn!("unbounded watch for {id:?} resolved without an exit; re-watching");
}
}
#[cfg(all(test, windows))]
pub(crate) mod fault_observer {
use std::sync::mpsc::Sender;
use std::sync::Mutex;
static RELEASE_TX: Mutex<Option<Sender<()>>> = Mutex::new(None);
pub(crate) fn install_release_observer(tx: Sender<()>) {
*RELEASE_TX.lock().unwrap() = Some(tx);
}
pub(crate) fn notify_released() {
if let Some(tx) = RELEASE_TX.lock().unwrap().as_ref() {
let _ = tx.send(());
}
}
}
#[cfg(target_os = "linux")]
async fn exit_watch(id: ProcessId) -> Result<(), Error> {
use ::tokio::io::unix::AsyncFd;
use ::tokio::io::Interest;
let Some(pidfd) = crate::wait::backend::open_verified(id)? else {
return Ok(());
};
let afd = AsyncFd::with_interest(pidfd, Interest::READABLE | Interest::ERROR).map_err(Error::Io)?;
loop {
let mut guard = afd
.ready(Interest::READABLE | Interest::ERROR)
.await
.map_err(Error::Io)?;
match classify_pidfd_ready(guard.ready()) {
Some(verdict) => return verdict,
None => guard.clear_ready(), }
}
}
#[cfg(target_os = "linux")]
fn classify_pidfd_ready(ready: ::tokio::io::Ready) -> Option<Result<(), Error>> {
if ready.is_error() {
return Some(Err(Error::Io(std::io::Error::other("pidfd poll returned POLLERR"))));
}
if ready.is_readable() || ready.is_read_closed() {
return Some(Ok(()));
}
None
}
#[cfg(target_os = "macos")]
async fn exit_watch(id: ProcessId) -> Result<(), Error> {
use ::tokio::io::unix::AsyncFd;
use ::tokio::io::Interest;
let Some(kq) = crate::wait::backend::arm_proc_exit(id)? else {
return Ok(());
};
let afd = AsyncFd::with_interest(KqueueFd(kq), Interest::READABLE).map_err(Error::Io)?;
watch_readable(&afd, crate::wait::backend::drain_proc_exit).await
}
#[cfg(target_os = "macos")]
struct KqueueFd(nix::sys::event::Kqueue);
#[cfg(target_os = "macos")]
impl std::os::fd::AsRawFd for KqueueFd {
fn as_raw_fd(&self) -> std::os::fd::RawFd {
use std::os::fd::AsFd;
self.0.as_fd().as_raw_fd()
}
}
#[cfg(target_os = "macos")]
async fn watch_readable<F>(afd: &::tokio::io::unix::AsyncFd<KqueueFd>, mut drain: F) -> Result<(), Error>
where
F: FnMut(&nix::sys::event::Kqueue) -> Result<Option<()>, Error>,
{
loop {
let mut guard = afd.readable().await.map_err(Error::Io)?;
match drain(&afd.get_ref().0)? {
Some(()) => return Ok(()),
None => guard.clear_ready(), }
}
}
#[cfg(test)]
#[path = "wait_tests.rs"]
mod wait_tests;