use std::io;
pub(crate) struct ProcessGuard {
write_fd: libc::c_int,
pid: libc::pid_t,
}
impl ProcessGuard {
pub(crate) fn new(group: u32) -> io::Result<Self> {
let mut pipe = [0; 2];
if unsafe { libc::pipe2(pipe.as_mut_ptr(), libc::O_CLOEXEC) } < 0 {
return Err(io::Error::last_os_error());
}
let pid = unsafe { libc::fork() };
if pid < 0 {
let error = io::Error::last_os_error();
unsafe {
libc::close(pipe[0]);
libc::close(pipe[1]);
}
return Err(error);
}
if pid == 0 {
unsafe {
libc::close(pipe[1]);
if pipe[0] != 3 {
if libc::dup2(pipe[0], 3) < 0 {
libc::_exit(1);
}
libc::close(pipe[0]);
}
libc::close(0);
libc::close(1);
libc::close(2);
if libc::syscall(libc::SYS_close_range, 4u32, u32::MAX, 0u32) < 0 {
let mut fd = 4;
while fd < 65536 {
libc::close(fd);
fd += 1;
}
}
let mut byte = 0u8;
loop {
let n = libc::read(3, (&mut byte as *mut u8).cast(), 1);
if n == 0 {
libc::kill(-(group as i32), libc::SIGKILL);
break;
}
if n > 0 {
break;
}
if *libc::__errno_location() != libc::EINTR {
libc::kill(-(group as i32), libc::SIGKILL);
break;
}
}
libc::_exit(0);
}
}
unsafe {
libc::close(pipe[0]);
}
Ok(Self {
write_fd: pipe[1],
pid,
})
}
}
impl Drop for ProcessGuard {
fn drop(&mut self) {
unsafe {
libc::close(self.write_fd);
while libc::waitpid(self.pid, std::ptr::null_mut(), 0) < 0 {
if *libc::__errno_location() != libc::EINTR {
break;
}
}
}
}
}