use std::ffi::OsStr;
use std::io;
use std::os::unix::process::CommandExt;
use std::process::{Command, Stdio};
#[cfg(target_os = "linux")]
extern "C" fn parent_died(_: libc::c_int) {}
pub fn supervise(emacs: &OsStr, parent: libc::pid_t) -> io::Result<bool> {
#[cfg(target_os = "linux")]
unsafe {
let mut action: libc::sigaction = std::mem::zeroed();
action.sa_sigaction = parent_died as *const () as libc::sighandler_t;
libc::sigemptyset(&mut action.sa_mask);
if libc::sigaction(libc::SIGTERM, &action, std::ptr::null_mut()) != 0
|| libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) != 0
|| libc::prctl(libc::PR_SET_CHILD_SUBREAPER, 1) != 0
{
return Err(io::Error::last_os_error());
}
}
if unsafe { libc::getppid() } != parent {
return Ok(false);
}
let mut emacs = Command::new(emacs)
.args(["-Q", "--batch", "-l", "./pass.el"])
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.process_group(0)
.spawn()?;
let group = emacs.id() as libc::pid_t;
let mut control = libc::pollfd {
fd: libc::STDIN_FILENO,
events: libc::POLLIN,
revents: 0,
};
let stopped = loop {
if unsafe { libc::poll(&mut control, 1, 20) } != 0 {
break false;
}
let mut info: libc::siginfo_t = unsafe { std::mem::zeroed() };
let ready = unsafe {
libc::waitid(
libc::P_PID,
group as libc::id_t,
&mut info,
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if ready == -1 || unsafe { info.si_pid() } != 0 {
break ready == 0;
}
};
unsafe { libc::kill(-group, libc::SIGKILL) };
let status = emacs.wait();
#[cfg(target_os = "linux")]
reap_adopted();
Ok(stopped && status?.success())
}
#[cfg(target_os = "linux")]
fn reap_adopted() {
loop {
if let Ok(children) = std::fs::read_to_string("/proc/thread-self/children") {
for pid in children
.split_whitespace()
.filter_map(|pid| pid.parse().ok())
{
unsafe { libc::kill(pid, libc::SIGKILL) };
}
}
if unsafe { libc::waitpid(-1, std::ptr::null_mut(), libc::WNOHANG) } == -1 {
break;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
}