Debian Codegraph @

src/unix.rs

raw symbols SCIP
1 //! Unix-only extensions, for sending signals.
2
3 use std::io;
4
5 pub trait SharedChildExt {
6 /// Send a signal to the child process with `libc::kill`. If the process
7 /// has already been waited on, this returns `Ok(())` and does nothing.
8 fn send_signal(&self, signal: libc::c_int) -> io::Result<()>;
9 }
10
11 impl SharedChildExt for super::SharedChild {
12 fn send_signal(&self, signal: libc::c_int) -> io::Result<()> {
13 let inner_guard = self.inner.lock().unwrap();
14 // Note that SharedChild::new calls try_wait_and_reap precisely so that we can assume "the
15 // child has been reaped if-and-only-if the state is Exited" right here. If we didn't have
16 // that guarantee, we'd need to call try_wait_and_reap right here, which would be an odd
17 // side effect. Unfortunately std::process::Child doesn't provide a way to query its exit
18 // status that doesn't potentially reap it as a side effect.
19 if let super::ChildState::Exited(_) = inner_guard.state {
20 return Ok(());
21 }
22 // The child is still running. Signal it. Holding the inner lock here prevents PID races,
23 // but note that calling SharedChild::id would reacquire it and deadlock.
24 let pid = inner_guard.child.id() as libc::pid_t;
25 match unsafe { libc::kill(pid, signal) } {
26 -1 => Err(io::Error::last_os_error()),
27 _ => Ok(()),
28 }
29 }
30 }
31
32 #[cfg(test)]
33 mod tests {
34 use super::SharedChildExt;
35 use crate::tests::*;
36 use crate::SharedChild;
37 use std::os::unix::process::ExitStatusExt;
38
39 #[test]
40 fn test_send_signal() {
41 let child = SharedChild::spawn(&mut sleep_forever_cmd()).unwrap();
42 child.send_signal(libc::SIGABRT).unwrap();
43 let status = child.wait().unwrap();
44 assert_eq!(Some(libc::SIGABRT), status.signal());
45 }
46 }