wait_timeout/lib.rs
1//! A crate to wait on a child process with a particular timeout.
2//!
3//! This crate is an implementation for Unix and Windows of the ability to wait
4//! on a child process with a timeout specified. On Windows the implementation
5//! is fairly trivial as it's just a call to `WaitForSingleObject` with a
6//! timeout argument, but on Unix the implementation is much more involved. The
7//! current implementation registers a `SIGCHLD` handler and initializes some
8//! global state. This handler also works within multi-threaded environments.
9//! If your application is otherwise handling `SIGCHLD` then bugs may arise.
10//!
11//! # Example
12//!
13//! ```no_run
14//! use std::process::Command;
15//! use wait_timeout::ChildExt;
16//! use std::time::Duration;
17//!
18//! let mut child = Command::new("foo").spawn().unwrap();
19//!
20//! let one_sec = Duration::from_secs(1);
21//! let status_code = match child.wait_timeout(one_sec).unwrap() {
22//! Some(status) => status.code(),
23//! None => {
24//! // child hasn't exited yet
25//! child.kill().unwrap();
26//! child.wait().unwrap().code()
27//! }
28//! };
29//! ```
30
31#![deny(missing_docs, warnings)]
32#![doc(html_root_url = "https://docs.rs/wait-timeout/0.1")]
33
34#[cfg(unix)]
35extern crate libc;
36
37use std::io;
38use std::process::{Child, ExitStatus};
39use std::time::Duration;
40
41#[cfg(unix)] #[path = "unix.rs"]
42mod imp;
43#[cfg(windows)] #[path = "windows.rs"]
44mod imp;
45
46/// Extension methods for the standard `std::process::Child` type.
47pub trait ChildExt {
48 /// Deprecated, use `wait_timeout` instead.
49 #[doc(hidden)]
50 fn wait_timeout_ms(&mut self, ms: u32) -> io::Result<Option<ExitStatus>> {
51 self.wait_timeout(Duration::from_millis(ms as u64))
52 }
53
54 /// Wait for this child to exit, timing out after the duration `dur` has
55 /// elapsed.
56 ///
57 /// If `Ok(None)` is returned then the timeout period elapsed without the
58 /// child exiting, and if `Ok(Some(..))` is returned then the child exited
59 /// with the specified exit code.
60 fn wait_timeout(&mut self, dur: Duration) -> io::Result<Option<ExitStatus>>;
61}
62
63impl ChildExt for Child {
64 fn wait_timeout(&mut self, dur: Duration) -> io::Result<Option<ExitStatus>> {
65 drop(self.stdin.take());
66 imp::wait_timeout(self, dur)
67 }
68}