|
| 1 | +use std::ffi::OsStr; |
| 2 | +use std::io; |
| 3 | +use std::process::{Child, Command}; |
| 4 | + |
| 5 | +#[cfg(windows)] |
| 6 | +const CREATE_NEW_PROCESS_GROUP: u32 = 0x00000200; |
| 7 | + |
| 8 | +/// Trait for sending interrupts/ctrl-c to child processes |
| 9 | +pub trait Interruptable: InterruptablePid { |
| 10 | + #[cfg(all(not(windows), not(unix)))] |
| 11 | + fn send_ctrl_c(&self) -> io::Result<()> { |
| 12 | + unimplemented!("Not implemented for this platform"); |
| 13 | + } |
| 14 | + |
| 15 | + #[cfg(unix)] |
| 16 | + fn send_ctrl_c(&self) -> io::Result<()> { |
| 17 | + if unsafe { libc::kill(self.pid() as i32, libc::SIGINT) } == 0 { |
| 18 | + Ok(()) |
| 19 | + } else { |
| 20 | + Err(io::Error::last_os_error()) |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + #[cfg(windows)] |
| 25 | + fn send_ctrl_c(&self) -> io::Result<()> { |
| 26 | + use windows_sys::Win32::System::Console::{CTRL_C_EVENT, GenerateConsoleCtrlEvent}; |
| 27 | + |
| 28 | + unsafe { |
| 29 | + // NOTE: This only works if the process is in a new process group |
| 30 | + if GenerateConsoleCtrlEvent(CTRL_C_EVENT, self.pid()) == 0 { |
| 31 | + Err(io::Error::last_os_error()) |
| 32 | + } else { |
| 33 | + Ok(()) |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +impl<T> Interruptable for T where T: InterruptablePid {} |
| 40 | + |
| 41 | +/// Trait for getting the pid of a child process |
| 42 | +pub trait InterruptablePid { |
| 43 | + fn pid(&self) -> u32; |
| 44 | +} |
| 45 | + |
| 46 | +impl InterruptablePid for Child { |
| 47 | + fn pid(&self) -> u32 { |
| 48 | + self.id() |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +/// Create a new interruptable command |
| 53 | +#[cfg(unix)] |
| 54 | +pub fn new_interruptable_command<S: AsRef<OsStr>>(program: S) -> Command { |
| 55 | + Command::new(program) |
| 56 | +} |
| 57 | + |
| 58 | +/// Create a new interruptable command |
| 59 | +#[cfg(windows)] |
| 60 | +pub fn new_interruptable_command<S: AsRef<OsStr>>(program: S) -> Command { |
| 61 | + use std::os::windows::process::CommandExt as _; |
| 62 | + |
| 63 | + let mut command = Command::new(program); |
| 64 | + command.creation_flags(CREATE_NEW_PROCESS_GROUP); |
| 65 | + command |
| 66 | +} |
| 67 | + |
| 68 | +#[cfg(test)] |
| 69 | +mod tests { |
| 70 | + use super::*; |
| 71 | + |
| 72 | + #[test] |
| 73 | + fn test_new_interruptable_command() { |
| 74 | + let mut command = new_interruptable_command("ping"); |
| 75 | + #[cfg(windows)] |
| 76 | + command.arg("-t"); |
| 77 | + command.arg("127.0.0.1"); |
| 78 | + |
| 79 | + let mut child = command.spawn().unwrap(); |
| 80 | + child.send_ctrl_c().unwrap(); |
| 81 | + child.wait().unwrap(); |
| 82 | + } |
| 83 | +} |
0 commit comments