1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
//! This crate allows terminating a process without a mutable reference. //! [`ProcessTerminator::terminate`] is designed to operate in this manner and //! is the reason this crate exists. It intentionally does not require a //! reference of any kind to the [`Child`] instance, allowing for maximal //! flexibility in working with processes. //! //! Typically, it is not possible to terminate a process during a call to //! [`Child::wait`] or [`Child::wait_with_output`] in another thread, since //! [`Child::kill`] takes a mutable reference. However, since this crate //! creates its own termination method, there is no issue, allowing cleanup //! after calling methods such as [`Terminator::wait_for_output_with_timeout`]. //! //! Crate [wait-timeout] has a similar purpose, but it does not provide the //! same flexibility. It does not allow reading the entire output of a process //! within the time limit or terminating a process based on other signals. This //! crate aims to fill in those gaps and simplify the implementation, now that //! [`Receiver::recv_timeout`] exists. //! //! # Implementation //! //! All traits are [sealed], meaning that they can only be implemented by this //! crate. Otherwise, backward compatibility would be more difficult to //! maintain for new features. //! //! # Examples //! //! ``` //! use std::io::Error as IoError; //! use std::io::ErrorKind as IoErrorKind; //! # use std::io::Result as IoResult; //! use std::process::Command; //! use std::process::Stdio; //! use std::time::Duration; //! //! use process_control::Terminator; //! //! # fn main() -> IoResult<()> { //! let process = Command::new("echo") //! .arg("hello") //! .stdout(Stdio::piped()) //! .spawn()?; //! //! let output = process //! .wait_for_output_with_timeout(Duration::from_secs(1))? //! .ok_or_else(|| { //! IoError::new(IoErrorKind::TimedOut, "Process timed out") //! })?; //! assert_eq!(b"hello", &output.stdout[..5]); //! # Ok(()) //! # } //! ``` //! //! [`Child`]: https://doc.rust-lang.org/std/process/struct.Child.html //! [`Child::kill`]: https://doc.rust-lang.org/std/process/struct.Child.html#method.kill //! [`Child::wait`]: https://doc.rust-lang.org/std/process/struct.Child.html#method.wait //! [`Child::wait_with_output`]: https://doc.rust-lang.org/std/process/struct.Child.html#method.wait_with_output //! [`ProcessTerminator::terminate`]: struct.ProcessTerminator.html#method.terminate //! [`Receiver::recv_timeout`]: https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html#method.recv_timeout //! [sealed]: https://rust-lang.github.io/api-guidelines/future-proofing.html#c-sealed //! [`Terminator::wait_for_output_with_timeout`]: trait.Terminator.html#tymethod.wait_for_output_with_timeout //! [wait-timeout]: https://crates.io/crates/wait-timeout #![doc( html_root_url = "https://docs.rs/process_control/*", test(attr(deny(warnings))) )] use std::io::ErrorKind as IoErrorKind; use std::io::Result as IoResult; use std::process::Child; use std::process::ExitStatus; use std::process::Output; use std::sync::mpsc; use std::thread::Builder as ThreadBuilder; use std::time::Duration; #[cfg(unix)] #[path = "unix.rs"] mod imp; #[cfg(windows)] #[path = "windows.rs"] mod imp; /// A wrapper that stores enough information to terminate a process. /// /// Instances can only be constructed using [`Terminator::terminator`]. /// /// [`Terminator::terminator`]: trait.Terminator.html#tymethod.terminator #[derive(Debug)] pub struct ProcessTerminator(imp::Process); impl ProcessTerminator { /// Terminates a process as immediately as the operating system allows. /// /// Behavior should be equivalent to calling [`Child::kill`] for the same /// process. The guarantees on the result of that method are also /// maintained; different [`ErrorKind`] variants may be returned in the /// future for the same type of failure. Allowing these breakages is /// required to be compatible with the [`Error`] type. /// /// # Panics /// /// Panics if the operating system gives conflicting indicators of whether /// the termination signal was accepted. /// /// # Examples /// /// ``` /// use std::io::Result as IoResult; /// use std::process::Command; /// use std::thread; /// use std::thread::JoinHandle; /// /// use process_control::Terminator; /// /// # fn main() -> IoResult<()> { /// let mut process = Command::new("echo").spawn()?; /// let process_terminator = process.terminator(); /// /// let thread: JoinHandle<IoResult<_>> = thread::spawn(move || { /// process.wait()?; /// println!("waited"); /// Ok(()) /// }); /// /// // [process.kill] requires a mutable reference. /// process_terminator.terminate()?; /// thread.join().expect("thread panicked")?; /// # Ok(()) /// # } /// ``` /// /// [`Child::kill`]: https://doc.rust-lang.org/std/process/struct.Child.html#method.kill /// [`Error`]: https://doc.rust-lang.org/std/io/struct.Error.html /// [`ErrorKind`]: https://doc.rust-lang.org/std/io/enum.ErrorKind.html #[inline] pub fn terminate(&self) -> IoResult<()> { self.0.terminate() } /// Terminates a process as immediately as the operating system allows, /// ignoring errors about the process no longer existing. /// /// For more information, see [`terminate`]. /// /// [`terminate`]: #method.terminate #[inline] pub fn terminate_if_necessary(&self) -> IoResult<()> { let result = self.terminate(); if let Err(error) = &result { if error.kind() == IoErrorKind::NotFound { return Ok(()); } } result } } fn run_with_timeout<TGetResultFn, TResult>( get_result_fn: TGetResultFn, time_limit: Duration, ) -> IoResult<Option<TResult>> where TGetResultFn: 'static + FnOnce() -> TResult + Send, TResult: 'static + Send, { let (result_sender, result_receiver) = mpsc::channel(); let _ = ThreadBuilder::new() .spawn(move || result_sender.send(get_result_fn()))?; Ok(result_receiver.recv_timeout(time_limit).ok()) } macro_rules! wait_and_terminate { ( $process:ident , $wait_fn:expr , $time_limit:ident $(,)? ) => {{ let process_terminator = $process.terminator(); let result = $wait_fn($process, $time_limit); // Errors terminating a process are less important than the result. let _ = process_terminator.terminate(); result }}; } /// Extensions to [`Child`] for easily killing processes. /// /// For more information, see [the module-level documentation][module]. /// /// [module]: index.html /// [`Child`]: https://doc.rust-lang.org/std/process/struct.Child.html pub trait Terminator: private::Sealed + Sized { /// Creates an instance of [`ProcessTerminator`] for this process. /// /// # Examples /// /// ``` /// # use std::io::Result as IoResult; /// use std::process::Command; /// /// use process_control::Terminator; /// /// # fn main() -> IoResult<()> { /// let process = Command::new("echo").spawn()?; /// # #[allow(unused_variables)] /// let process_terminator = process.terminator(); /// # Ok(()) /// # } /// ``` /// /// [`ProcessTerminator`]: struct.ProcessTerminator.html #[must_use] fn terminator(&self) -> ProcessTerminator; /// A convenience method for calling [`Child::wait`] with a timeout. /// /// As the `Child` must be consumed by this method, it is returned if the /// process finishes. The instance would be required to subsequently access /// [`Child::stdout`] or other fields. /// /// For more information, see [`wait_for_output_with_timeout`]. /// /// [`Child::stdout`]: https://doc.rust-lang.org/std/process/struct.Child.html#structfield.stdout /// [`Child::wait`]: https://doc.rust-lang.org/std/process/struct.Child.html#method.wait /// [`wait_for_output_with_timeout`]: #tymethod.wait_for_output_with_timeout fn wait_with_timeout( self, time_limit: Duration, ) -> IoResult<Option<(ExitStatus, Self)>>; /// A convenience method for calling [`Child::wait_with_output`] with a /// timeout. /// /// If the time limit expires before that method finishes, `Ok(None)` will /// be returned. The process will not be terminated, so it may be desirable /// to call [`ProcessTerminator::terminate_if_necessary`] afterward to free /// system resources. [`wait_for_output_with_terminating_timeout`] can be /// used to call that method automatically. /// /// This method will create a separate thread to run the method without /// blocking the current thread. /// /// # Examples /// /// ``` /// # use std::io::Result as IoResult; /// use std::process::Command; /// use std::time::Duration; /// /// use process_control::Terminator; /// /// # fn main() -> IoResult<()> { /// let process = Command::new("echo").spawn()?; /// let process_terminator = process.terminator(); /// /// let result = /// process.wait_for_output_with_timeout(Duration::from_secs(1))?; /// process_terminator.terminate_if_necessary()?; /// /// match result { /// Some(output) => assert!(output.status.success()), /// None => panic!("process timed out"), /// } /// # Ok(()) /// # } /// ``` /// /// [`Child::wait_with_output`]: https://doc.rust-lang.org/std/process/struct.Child.html#method.wait_with_output /// [`ProcessTerminator::terminate_if_necessary`]: struct.ProcessTerminator.html#method.terminate_if_necessary /// [`wait_for_output_with_terminating_timeout`]: #tymethod.wait_for_output_with_terminating_timeout fn wait_for_output_with_timeout( self, time_limit: Duration, ) -> IoResult<Option<Output>>; /// A convenience method for calling [`wait_with_timeout`] and terminating /// the process if it exceeds the time limit. /// /// For more information, see [`wait_for_output_with_terminating_timeout`]. /// /// [`wait_with_timeout`]: #tymethod.wait_with_timeout /// [`wait_for_output_with_terminating_timeout`]: #tymethod.wait_for_output_with_terminating_timeout fn wait_with_terminating_timeout( self, time_limit: Duration, ) -> IoResult<Option<(ExitStatus, Self)>>; /// A convenience method for calling [`wait_for_output_with_timeout`] and /// terminating the process if it exceeds the time limit. /// /// # Examples /// /// ``` /// # use std::io::Result as IoResult; /// use std::process::Command; /// use std::time::Duration; /// /// use process_control::Terminator; /// /// # fn main() -> IoResult<()> { /// let process = Command::new("echo").spawn()?; /// match process /// .wait_for_output_with_terminating_timeout(Duration::from_secs(1))? /// { /// Some(output) => assert!(output.status.success()), /// None => panic!("process timed out"), /// } /// # Ok(()) /// # } /// ``` /// /// [`wait_for_output_with_timeout`]: #tymethod.wait_for_output_with_timeout fn wait_for_output_with_terminating_timeout( self, time_limit: Duration, ) -> IoResult<Option<Output>>; } impl Terminator for Child { #[inline] fn terminator(&self) -> ProcessTerminator { ProcessTerminator(imp::Process::new(self)) } #[inline] fn wait_with_timeout( mut self, time_limit: Duration, ) -> IoResult<Option<(ExitStatus, Self)>> { run_with_timeout(|| (self.wait(), self), time_limit)? .map(|(exit_status, process)| exit_status.map(|x| (x, process))) .transpose() } #[inline] fn wait_for_output_with_timeout( self, time_limit: Duration, ) -> IoResult<Option<Output>> { run_with_timeout(|| self.wait_with_output(), time_limit)?.transpose() } #[inline] fn wait_with_terminating_timeout( self, time_limit: Duration, ) -> IoResult<Option<(ExitStatus, Self)>> { wait_and_terminate!(self, Self::wait_with_timeout, time_limit) } #[inline] fn wait_for_output_with_terminating_timeout( self, time_limit: Duration, ) -> IoResult<Option<Output>> { wait_and_terminate!( self, Self::wait_for_output_with_timeout, time_limit, ) } } mod private { use std::process::Child; pub trait Sealed {} impl Sealed for Child {} }