use std::time::{Duration, Instant};
use nix::sys::event::{EvFlags, EventFilter, FilterFlag, KEvent, Kqueue};
use crate::error::Error;
use crate::identity::ProcessId;
fn placeholder() -> KEvent {
KEvent::new(0, EventFilter::EVFILT_PROC, EvFlags::empty(), FilterFlag::empty(), 0, 0)
}
pub(crate) fn add_with_receipt(kq: &Kqueue, change: KEvent) -> Result<i64, Error> {
let mut receipt = [placeholder()];
let n = kq
.kevent(&[change], &mut receipt, None)
.map_err(|e| Error::Io(e.into()))?;
if n != 1 {
return Err(Error::Io(std::io::Error::other(
"kqueue EV_RECEIPT returned no receipt event",
)));
}
Ok(receipt[0].data() as i64)
}
pub(crate) fn arm_note_exit_on(kq: &Kqueue, pid: u32) -> Result<Option<()>, Error> {
let change = KEvent::new(
pid as usize,
EventFilter::EVFILT_PROC,
EvFlags::EV_ADD | EvFlags::EV_RECEIPT,
FilterFlag::NOTE_EXIT,
0,
0,
);
let add_result = add_with_receipt(kq, change)?;
if add_result == libc::ESRCH as i64 {
return Ok(None); }
if add_result != 0 {
return Err(Error::Io(std::io::Error::from_raw_os_error(add_result as i32)));
}
Ok(Some(()))
}
pub(crate) fn arm_proc_exit(id: ProcessId) -> Result<Option<Kqueue>, Error> {
let kq = Kqueue::new().map_err(|e| Error::Io(e.into()))?;
if arm_note_exit_on(&kq, id.pid())?.is_none() {
return Ok(None); }
match id.exists() {
crate::identity::Existence::Present => Ok(Some(kq)),
crate::identity::Existence::Gone => Ok(None), crate::identity::Existence::Unknown => {
log::warn!(
"wait: pid {} identity could not be confirmed; its exit cannot be observed",
id.pid()
);
Err(Error::Unassessable {
detail: format!(
"pid {} identity could not be confirmed; its exit cannot be observed",
id.pid()
),
source: None,
})
}
}
}
#[cfg_attr(not(feature = "tokio"), allow(dead_code))] pub(crate) fn drain_proc_exit(kq: &Kqueue) -> Result<Option<()>, Error> {
let zero = libc::timespec { tv_sec: 0, tv_nsec: 0 };
let mut events = [placeholder()];
loop {
match kq.kevent(&[], &mut events, Some(zero)) {
Ok(0) => return Ok(None), Ok(_) => {
if events[0].flags().contains(EvFlags::EV_ERROR) {
return Err(Error::Io(std::io::Error::from_raw_os_error(events[0].data() as i32)));
}
return Ok(Some(())); }
Err(nix::errno::Errno::EINTR) => continue,
Err(e) => return Err(Error::Io(e.into())),
}
}
}
pub(crate) fn block_until_exit(id: ProcessId, deadline: Option<Option<Instant>>) -> Result<bool, Error> {
let Some(kq) = arm_proc_exit(id)? else {
return Ok(true);
};
block_on_kqueue(&kq, deadline, false, |event| {
if event.flags().contains(EvFlags::EV_ERROR) {
return Err(Error::Io(std::io::Error::from_raw_os_error(event.data() as i32)));
}
Ok(Some(true)) })
}
pub(crate) fn block_on_kqueue<T: Copy>(
kq: &Kqueue,
deadline: Option<Option<Instant>>,
on_timeout: T,
mut interpret: impl FnMut(&KEvent) -> Result<Option<T>, Error>,
) -> Result<T, Error> {
let mut events = [placeholder()];
loop {
let remaining = crate::wait::remaining(deadline);
let already_elapsed = remaining == Some(Duration::ZERO);
let timeout = remaining.map(|d| libc::timespec {
tv_sec: d.as_secs().min(i64::MAX as u64) as libc::time_t,
tv_nsec: d.subsec_nanos() as libc::c_long,
});
match kq.kevent(&[], &mut events, timeout) {
Ok(0) => return Ok(on_timeout), Ok(_) => {
if let Some(verdict) = interpret(&events[0])? {
return Ok(verdict);
}
if already_elapsed {
return Ok(on_timeout);
}
}
Err(nix::errno::Errno::EINTR) => continue,
Err(e) => return Err(Error::Io(e.into())),
}
}
}
pub(crate) fn kill(id: ProcessId) -> Result<(), Error> {
use nix::sys::signal::{kill as nix_kill, Signal};
use nix::unistd::Pid;
match ProcessId::of(id.pid()) {
crate::identity::Resolved::Found(live) if live == id => {}
crate::identity::Resolved::Found(_) | crate::identity::Resolved::Gone => return Ok(()),
crate::identity::Resolved::Unknown => {
log::warn!(
"wait: pid {} identity could not be confirmed - no signal was sent",
id.pid()
);
return Err(Error::Unassessable {
detail: format!("pid {} identity could not be confirmed; no signal was sent", id.pid()),
source: None,
});
}
}
let Some(target) = crate::identity::probe::signal_target(id.pid()) else {
log::warn!(
"wait: pid {} is not a single-process signal target - not signaled",
id.pid()
);
return Err(Error::Unassessable {
detail: format!("pid {} is not a signalable single-process target", id.pid()),
source: None,
});
};
match nix_kill(Pid::from_raw(target), Signal::SIGKILL) {
Ok(()) => Ok(()),
Err(nix::errno::Errno::ESRCH) => Ok(()), Err(e) => Err(Error::Io(e.into())), }
}
pub(crate) fn terminate(id: ProcessId) -> Result<(), Error> {
use nix::sys::signal::{kill as nix_kill, Signal};
use nix::unistd::Pid;
match ProcessId::of(id.pid()) {
crate::identity::Resolved::Found(live) if live == id => {}
crate::identity::Resolved::Found(_) | crate::identity::Resolved::Gone => return Ok(()),
crate::identity::Resolved::Unknown => {
log::warn!(
"wait: pid {} identity could not be confirmed - no signal was sent",
id.pid()
);
return Err(Error::Unassessable {
detail: format!("pid {} identity could not be confirmed; no signal was sent", id.pid()),
source: None,
});
}
}
let Some(target) = crate::identity::probe::signal_target(id.pid()) else {
log::warn!(
"wait: pid {} is not a single-process signal target - not signaled",
id.pid()
);
return Err(Error::Unassessable {
detail: format!("pid {} is not a signalable single-process target", id.pid()),
source: None,
});
};
match nix_kill(Pid::from_raw(target), Signal::SIGTERM) {
Ok(()) => Ok(()),
Err(nix::errno::Errno::ESRCH) => Ok(()),
Err(e) => Err(Error::Io(e.into())),
}
}
#[cfg(test)]
#[path = "macos_tests.rs"]
mod macos_tests;