| 1 |
use std::io; |
| 2 |
use std::mem::MaybeUninit; |
| 3 |
use std::process::Child; |
| 4 |
#[cfg(feature = "timeout")] |
| 5 |
use std::time::Instant; |
| 6 |
|
| 7 |
|
| 8 |
#[derive(Copy, Clone)] |
| 9 |
pub struct Handle(u32); |
| 10 |
|
| 11 |
pub fn get_handle(child: &Child) -> Handle { |
| 12 |
Handle(child.id()) |
| 13 |
} |
| 14 |
|
| 15 |
|
| 16 |
pub fn wait_noreap(handle: Handle) -> io::Result<()> { |
| 17 |
loop { |
| 18 |
let mut siginfo = MaybeUninit::zeroed(); |
| 19 |
let ret = unsafe { |
| 20 |
libc::waitid( |
| 21 |
libc::P_PID, |
| 22 |
handle.0 as libc::id_t, |
| 23 |
siginfo.as_mut_ptr(), |
| 24 |
libc::WEXITED | libc::WNOWAIT, |
| 25 |
) |
| 26 |
}; |
| 27 |
if ret == 0 { |
| 28 |
return Ok(()); |
| 29 |
} |
| 30 |
let error = io::Error::last_os_error(); |
| 31 |
if error.kind() != io::ErrorKind::Interrupted { |
| 32 |
return Err(error); |
| 33 |
} |
| 34 |
|
| 35 |
} |
| 36 |
} |
| 37 |
|
| 38 |
|
| 39 |
pub fn try_wait_noreap(handle: Handle) -> io::Result<bool> { |
| 40 |
let mut siginfo: libc::siginfo_t; |
| 41 |
let ret = unsafe { |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
siginfo = std::mem::zeroed(); |
| 55 |
libc::waitid( |
| 56 |
libc::P_PID, |
| 57 |
handle.0 as libc::id_t, |
| 58 |
&mut siginfo, |
| 59 |
libc::WEXITED | libc::WNOWAIT | libc::WNOHANG, |
| 60 |
) |
| 61 |
}; |
| 62 |
if ret != 0 { |
| 63 |
|
| 64 |
Err(io::Error::last_os_error()) |
| 65 |
} else if siginfo.si_signo == libc::SIGCHLD { |
| 66 |
|
| 67 |
Ok(true) |
| 68 |
} else if siginfo.si_signo == 0 { |
| 69 |
|
| 70 |
Ok(false) |
| 71 |
} else { |
| 72 |
|
| 73 |
|
| 74 |
Err(io::Error::other(format!( |
| 75 |
"unexpected si_signo from waitid: {}", |
| 76 |
siginfo.si_signo |
| 77 |
))) |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
|
| 82 |
#[cfg(feature = "timeout")] |
| 83 |
pub fn wait_deadline_noreap(handle: Handle, deadline: Instant) -> io::Result<bool> { |
| 84 |
let mut sigchld_waiter = sigchld::Waiter::new()?; |
| 85 |
loop { |
| 86 |
|
| 87 |
if try_wait_noreap(handle)? { |
| 88 |
return Ok(true); |
| 89 |
} |
| 90 |
|
| 91 |
if deadline < Instant::now() { |
| 92 |
return Ok(false); |
| 93 |
} |
| 94 |
|
| 95 |
|
| 96 |
sigchld_waiter.wait_deadline(deadline)?; |
| 97 |
} |
| 98 |
} |