use std::{ffi::CString, io, os::unix::ffi::OsStrExt, path::Path};
pub(super) fn signal(pid: u32, signal: i32, group: bool) -> io::Result<()> {
let pid = i32::try_from(pid).map_err(|_| io::ErrorKind::InvalidInput)?;
let rc = unsafe { libc::kill(if group { -pid } else { pid }, signal) };
if rc == 0 {
return Ok(());
}
let error = io::Error::last_os_error();
if error.raw_os_error() == Some(libc::ESRCH) {
Ok(())
} else {
Err(error)
}
}
pub(super) fn fifo(path: &Path) -> io::Result<()> {
let path = CString::new(path.as_os_str().as_bytes())?;
if unsafe { libc::mkfifo(path.as_ptr(), 0o600) } == 0 {
Ok(())
} else {
Err(io::Error::last_os_error())
}
}
pub(super) fn exited(pid: u32) -> io::Result<bool> {
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let rc = unsafe {
libc::waitid(
libc::P_PID,
pid,
&raw mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if rc != 0 {
return Err(io::Error::last_os_error());
}
Ok(unsafe { info.si_pid() } != 0)
}
pub(super) fn reap(pid: u32) -> io::Result<std::process::ExitStatus> {
use std::os::unix::process::ExitStatusExt;
let pid = i32::try_from(pid).map_err(|_| io::ErrorKind::InvalidInput)?;
loop {
let mut status = 0;
if unsafe { libc::waitpid(pid, &raw mut status, 0) } == pid {
return Ok(std::process::ExitStatus::from_raw(status));
}
let error = io::Error::last_os_error();
if error.kind() != io::ErrorKind::Interrupted {
return Err(error);
}
}
}
pub(super) fn cleanup_exited_group(pid: u32) -> io::Result<()> {
match signal(pid, libc::SIGKILL, true) {
#[cfg(target_os = "macos")]
Err(e) if e.raw_os_error() == Some(libc::EPERM) => Ok(()),
result => result,
}
}