1 use std;
2 use std::io;
3 use std::process::Child;
4
5 // A handle on Unix is just the PID.
6 pub struct Handle(u32);
7
get_handle(child: &Child) -> Handle8 pub fn get_handle(child: &Child) -> Handle {
9 Handle(child.id())
10 }
11
12 // This blocks until a child exits, without reaping the child.
wait_without_reaping(handle: Handle) -> io::Result<()>13 pub fn wait_without_reaping(handle: Handle) -> io::Result<()> {
14 loop {
15 let ret = unsafe {
16 let mut siginfo = std::mem::zeroed();
17 libc::waitid(
18 libc::P_PID,
19 handle.0 as libc::id_t,
20 &mut siginfo,
21 libc::WEXITED | libc::WNOWAIT,
22 )
23 };
24 if ret == 0 {
25 return Ok(());
26 }
27 let error = io::Error::last_os_error();
28 if error.kind() != io::ErrorKind::Interrupted {
29 return Err(error);
30 }
31 // We were interrupted. Loop and retry.
32 }
33 }
34
35 // This checks whether the child has already exited, without reaping the child.
try_wait_without_reaping(handle: Handle) -> io::Result<bool>36 pub fn try_wait_without_reaping(handle: Handle) -> io::Result<bool> {
37 let mut siginfo: libc::siginfo_t;
38 let ret = unsafe {
39 // Darwin doesn't touch the siginfo_t struct if the child hasn't exited
40 // yet. It expects us to have zeroed it ahead of time:
41 //
42 // The state of the siginfo structure in this case
43 // is undefined. Some implementations bzero it, some
44 // (like here) leave it untouched for efficiency.
45 //
46 // Thus the most portable check for "no matching pid with
47 // WNOHANG" is to store a zero into si_pid before
48 // invocation, then check for a non-zero value afterwards.
49 //
50 // https://github.com/opensource-apple/xnu/blob/0a798f6738bc1db01281fc08ae024145e84df927/bsd/kern/kern_exit.c#L2150-L2156
51 siginfo = std::mem::zeroed();
52 libc::waitid(
53 libc::P_PID,
54 handle.0 as libc::id_t,
55 &mut siginfo,
56 libc::WEXITED | libc::WNOWAIT | libc::WNOHANG,
57 )
58 };
59 if ret != 0 {
60 // EINTR should be impossible here
61 Err(io::Error::last_os_error())
62 } else if siginfo.si_signo == libc::SIGCHLD {
63 // The child has exited.
64 Ok(true)
65 } else if siginfo.si_signo == 0 {
66 // The child has not exited.
67 Ok(false)
68 } else {
69 // This should be impossible if we called waitid correctly. But it will
70 // show up on macOS if we forgot to zero the siginfo_t above, for example.
71 Err(io::Error::new(
72 io::ErrorKind::Other,
73 format!("unexpected si_signo from waitid: {}", siginfo.si_signo),
74 ))
75 }
76 }
77