wait-timeout-0.1.5/.gitignore01006640001750000175000000000022125734253340014362 0ustar0000000000000000target Cargo.lock wait-timeout-0.1.5/.travis.yml01006640001750000175000000002074130141045420014476 0ustar0000000000000000language: rust rust: - stable - beta - nightly sudo: false before_script: - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH script: - cargo build --verbose - cargo test --verbose - cargo doc --no-deps after_success: - travis-cargo --only nightly doc-upload env: global: secure: "jzqfkE1zPzwe/ofghiKvN/3Vo/kLYN+pDzSIOGL3Xnum5eayUf87Uae1UuAbgXfKm2/meXWizMjcVrBeNrfxRi3qvaM+MLGAR4YK4G2Z91Uuf3edHF/uu7rhhaLWsPOkb4qDH/lBRIsKhDMpLXuc/5DSqZdPVQa8H+5ULtQFwWkets8BGfPu+vCgHeGb/lMgm56BnedUBqO7hAI1dYEn55R3L4rwgkMDWTyiAczL3RBuFJrHIAY5C+8JbkvvL+4+9v3oulJgXDQnQYkdNiZE0BjCvj+w0J2W1C1E8vgX3wB71RbQ+ijh1f98RoR6SqDqWE5eZDrl+L8V3sP2BIK/yhCrUCwpysQXW6Lo9/aVEDVPTB2KxvVjGb9jFwYyvZLuB0Q1t7UlOIo3MXIZLvMSZT99tfOZ5f1MdQt0C+ACZ6LKTAF0VUxmEGequ8kBBj+uDnHiIeWzkCJVTpqwTuJcprEPNCUx6T2pxyIZkyTS2DzviBbzLE/fLahm/+RJrkraH3lD4tLiTC7IckNrmnufx78oIsbYxdYp4Bo5cASLiRTVL9BS3yJ5So/Qr/C5pQ48PjKokyBDXX01U9SA6K3nxJ5tO+/q4d77utSaG9kb1UQpwNojpMBTBC1OFVbb/2nlOmf2BKLpciNCBmUHJnq/+By9l0f0eRS/0JanFBdIDkM=" notifications: email: on_success: never os: - linux - osx wait-timeout-0.1.5/Cargo.toml01006640001750000175000000002151130575451230014324 0ustar0000000000000000# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g. crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "wait-timeout" version = "0.1.5" authors = ["Alex Crichton "] description = "A crate to wait on a child process with a timeout specified across Unix and\nWindows platforms.\n" homepage = "https://github.com/alexcrichton/wait-timeout" documentation = "https://docs.rs/wait-timeout" readme = "README.md" categories = ["os"] license = "MIT/Apache-2.0" repository = "https://github.com/alexcrichton/wait-timeout" [dependencies.libc] version = "0.2" [badges.appveyor] repository = "alexcrichton/wait-timeout" [badges.travis-ci] repository = "alexcrichton/wait-timeout" wait-timeout-0.1.5/Cargo.toml.orig01006640001750000175000000001134130575451230015263 0ustar0000000000000000[package] name = "wait-timeout" version = "0.1.5" authors = ["Alex Crichton "] license = "MIT/Apache-2.0" readme = "README.md" repository = "https://github.com/alexcrichton/wait-timeout" homepage = "https://github.com/alexcrichton/wait-timeout" documentation = "https://docs.rs/wait-timeout" description = """ A crate to wait on a child process with a timeout specified across Unix and Windows platforms. """ categories = ["os"] [badges] travis-ci = { repository = "alexcrichton/wait-timeout" } appveyor = { repository = "alexcrichton/wait-timeout" } [dependencies] libc = "0.2" wait-timeout-0.1.5/LICENSE-APACHE01006640001750000175000000025137125734276000014332 0ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. wait-timeout-0.1.5/LICENSE-MIT01006640001750000175000000002041125734276000014027 0ustar0000000000000000Copyright (c) 2014 Alex Crichton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. wait-timeout-0.1.5/README.md01006640001750000175000000000736130474365140013664 0ustar0000000000000000# wait-timeout [![Build Status](https://travis-ci.org/alexcrichton/wait-timeout.svg?branch=master)](https://travis-ci.org/alexcrichton/wait-timeout) [![Build status](https://ci.appveyor.com/api/projects/status/3t5mh1c8i4lnolma?svg=true)](https://ci.appveyor.com/project/alexcrichton/wait-timeout) [Documentation](https://docs.rs/wait-timeout) Rust crate for waiting on a `Child` process with a timeout specified. ```toml # Cargo.toml [dependencies] wait-timeout = "0.1" ``` wait-timeout-0.1.5/appveyor.yml01006640001750000175000000000760127770242020014766 0ustar0000000000000000environment: matrix: - TARGET: x86_64-pc-windows-msvc - TARGET: i686-pc-windows-msvc - TARGET: i686-pc-windows-gnu install: - ps: Start-FileDownload "https://static.rust-lang.org/dist/rust-nightly-${env:TARGET}.exe" - rust-nightly-%TARGET%.exe /VERYSILENT /NORESTART /DIR="C:\Program Files (x86)\Rust" - SET PATH=%PATH%;C:\Program Files (x86)\Rust\bin - SET PATH=%PATH%;C:\MinGW\bin - rustc -V - cargo -V build: false test_script: - cargo test --verbose --target %TARGET% wait-timeout-0.1.5/src/bin/exit.rs01006640001750000175000000000156126142376270015262 0ustar0000000000000000fn main() { let code = std::env::args().nth(1).unwrap().parse().unwrap(); std::process::exit(code); } wait-timeout-0.1.5/src/bin/sleep.rs01006640001750000175000000000216126533107060015407 0ustar0000000000000000fn main() { let amt = std::env::args().nth(1).unwrap().parse().unwrap(); std::thread::sleep(std::time::Duration::from_millis(amt)); } wait-timeout-0.1.5/src/lib.rs01006640001750000175000000010512130474365410014301 0ustar0000000000000000//! A crate to wait on a child process with a particular timeout. //! //! This crate is an implementation for Unix and Windows of the ability to wait //! on a child process with a timeout specified. On Windows the implementation //! is fairly trivial as it's just a call to `WaitForSingleObject` with a //! timeout argument, but on Unix the implementation is much more involved. The //! current implementation registeres a `SIGCHLD` handler and initializes some //! global state. If your application is otherwise handling `SIGCHLD` then bugs //! may arise. //! //! # Example //! //! ```no_run //! use std::process::Command; //! use wait_timeout::ChildExt; //! use std::time::Duration; //! //! let mut child = Command::new("foo").spawn().unwrap(); //! //! let one_sec = Duration::from_secs(1); //! let status_code = match child.wait_timeout(one_sec).unwrap() { //! Some(status) => status.code(), //! None => { //! // child hasn't exited yet //! child.kill().unwrap(); //! child.wait().unwrap().code() //! } //! }; //! ``` #![deny(missing_docs, warnings)] #![doc(html_root_url = "https://docs.rs/wait-timeout/0.1")] extern crate libc; use std::fmt; use std::io; use std::process::Child; use std::time::Duration; /// Exit status from a child process. /// /// This type mirrors that in `std::process` but currently must be distinct as /// the one in `std::process` cannot be created. #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct ExitStatus(imp::ExitStatus); #[cfg(unix)] #[path = "unix.rs"] mod imp; #[cfg(windows)] #[path = "windows.rs"] mod imp; /// Extension methods for the standard `std::process::Child` type. pub trait ChildExt { /// Deprecated, use `wait_timeout` instead. #[doc(hidden)] fn wait_timeout_ms(&mut self, ms: u32) -> io::Result> { self.wait_timeout(Duration::from_millis(ms as u64)) } /// Wait for this child to exit, timing out after `ms` milliseconds have /// elapsed. /// /// If `Ok(None)` is returned then the timeout period elapsed without the /// child exiting, and if `Ok(Some(..))` is returned then the child exited /// with the specified exit code. /// /// # Warning /// /// Currently this function must be called with great care. If the child /// has already been waited on (e.g. `wait` returned a success) then this /// function will either wait on another process or fail spuriously on some /// platforms. This function may only be reliably called if the process has /// not already been waited on. /// /// Additionally, once this method completes the original child cannot be /// waited on reliably. The `wait` method on the original child may return /// spurious errors or have odd behavior on some platforms. If this /// function returns `Ok(None)`, however, it is safe to wait on the child /// with the normal libstd `wait` method. fn wait_timeout(&mut self, dur: Duration) -> io::Result>; } impl ChildExt for Child { fn wait_timeout(&mut self, dur: Duration) -> io::Result> { imp::wait_timeout(self, dur).map(|m| m.map(ExitStatus)) } } impl ExitStatus { /// Returns whether this exit status represents a successful execution. /// /// This typically means that the child process successfully exited with a /// status code of 0. pub fn success(&self) -> bool { self.0.success() } /// Returns the code associated with the child's exit event. /// /// On Unix this can return `None` if the child instead exited because of a /// signal. On Windows, however, this will always return `Some`. pub fn code(&self) -> Option { self.0.code() } /// Returns the Unix signal which terminated this process. /// /// Note that on Windows this will always return `None` and on Unix this /// will return `None` if the process successfully exited otherwise. pub fn unix_signal(&self) -> Option { self.0.unix_signal() } } impl fmt::Display for ExitStatus { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if let Some(c) = self.code() { write!(f, "exit code: {}", c) } else if let Some(s) = self.unix_signal() { write!(f, "signal: {}", s) } else { write!(f, "exit status: unknown") } } } wait-timeout-0.1.5/src/unix.rs01006640001750000175000000027221130575450720014524 0ustar0000000000000000//! Unix implementation of waiting for children with timeouts //! //! On unix, wait() and its friends have no timeout parameters, so there is //! no way to time out a thread in wait(). From some googling and some //! thinking, it appears that there are a few ways to handle timeouts in //! wait(), but the only real reasonable one for a multi-threaded program is //! to listen for SIGCHLD. //! //! With this in mind, the waiting mechanism with a timeout only uses //! waitpid() with WNOHANG, but otherwise all the necessary blocking is done by //! waiting for a SIGCHLD to arrive (and that blocking has a timeout). Note, //! however, that waitpid() is still used to actually reap the child. //! //! Signal handling is super tricky in general, and this is no exception. Due //! to the async nature of SIGCHLD, we use the self-pipe trick to transmit //! data out of the signal handler to the rest of the application. #![allow(bad_style)] use std::cmp; use std::collections::HashMap; use std::fs::File; use std::io::{self, Write, Read}; use std::mem; use std::os::unix::prelude::*; use std::process::Child; use std::sync::{Once, ONCE_INIT, Mutex}; use std::time::Duration; use libc::{self, c_int}; static INIT: Once = ONCE_INIT; static mut STATE: *mut State = 0 as *mut _; struct State { prev: libc::sigaction, write: File, read: File, map: Mutex, } type StateMap = HashMap)>; #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct ExitStatus(c_int); pub fn wait_timeout(child: &mut Child, dur: Duration) -> io::Result> { INIT.call_once(State::init); unsafe { (*STATE).wait_timeout(child, dur) } } // Do $value as type_of($target) macro_rules! _as { ($value:expr, $target:expr) => ( { let mut x = $target; x = $value as _; x } ) } impl State { #[allow(unused_assignments)] fn init() { unsafe { // Create our "self pipe" and then set both ends to nonblocking // mode. let (read, write) = file_pair().unwrap(); let mut state = Box::new(State { prev: mem::zeroed(), write: write, read: read, map: Mutex::new(HashMap::new()), }); // Register our sigchld handler let mut new: libc::sigaction = mem::zeroed(); new.sa_sigaction = sigchld_handler as usize; // FIXME: remove this workaround when the PR to libc get merged and released // // This is a workaround for the type mismatch in the definition of SA_* // constants for android. See https://github.com/rust-lang/libc/pull/511 // let sa_flags = new.sa_flags; new.sa_flags = _as!(libc::SA_NOCLDSTOP, sa_flags) | _as!(libc::SA_RESTART, sa_flags) | _as!(libc::SA_SIGINFO, sa_flags); assert_eq!(libc::sigaction(libc::SIGCHLD, &new, &mut state.prev), 0); STATE = mem::transmute(state); } } fn wait_timeout(&self, child: &mut Child, dur: Duration) -> io::Result> { // First up, prep our notification pipe which will tell us when our // child has been reaped (other threads may signal this pipe). let (read, write) = try!(file_pair()); let id = child.id() as c_int; // Next, take a lock on the map of children currently waiting. Right // after this, **before** we add ourselves to the map, we check to see // if our child has actually already exited via a `try_wait`. If the // child has exited then we return immediately as we'll never otherwise // receive a SIGCHLD notification. // // If the wait reports the child is still running, however, we add // ourselves to the map and then block in `select` waiting for something // to happen. let mut map = self.map.lock().unwrap(); if let Some(status) = try!(try_wait(id)) { return Ok(Some(status)) } assert!(map.insert(id, (write, None)).is_none()); drop(map); // Alright, we're guaranteed that we'll eventually get a SIGCHLD due // to our `try_wait` failing, and we're also guaranteed that we'll // get notified about this because we're in the map. Next up wait // for an event. // // Note that this happens in a loop for two reasons; we could // receive EINTR or we could pick up a SIGCHLD for other threads but not // actually be ready oureslves. let end_time = now_ns(); loop { let cur_time = now_ns(); let nanos = cur_time - end_time; let elapsed = Duration::new(nanos / 1_000_000_000, (nanos % 1_000_000_000) as u32); if elapsed >= dur { break } let timeout = dur - elapsed; let mut timeout = libc::timeval { tv_sec: timeout.as_secs() as libc::time_t, tv_usec: (timeout.subsec_nanos() / 1000) as libc::suseconds_t, }; let r = unsafe { let mut set: libc::fd_set = mem::uninitialized(); libc::FD_ZERO(&mut set); libc::FD_SET(self.read.as_raw_fd(), &mut set); libc::FD_SET(read.as_raw_fd(), &mut set); let max = cmp::max(self.read.as_raw_fd(), read.as_raw_fd()) + 1; libc::select(max, &mut set, 0 as *mut _, 0 as *mut _, &mut timeout) }; let timeout = match r { 0 => true, 1 | 2 => false, n => { let err = io::Error::last_os_error(); if err.kind() == io::ErrorKind::Interrupted { continue } else { panic!("error in select = {}: {}", n, err) } } }; // Now that something has happened, we need to process what actually // happened. There's are three reasons we could have woken up: // // 1. The file descriptor in our SIGCHLD handler was written to. // This means that a SIGCHLD was received and we need to poll the // entire list of waiting processes to figure out which ones // actually exited. // 2. Our file descriptor was written to. This means that another // thread reaped our child and listed the exit status in the // local map. // 3. We timed out. This means we need to remove ourselves from the // map and simply carry on. // // In the case that a SIGCHLD signal was received, we do that // processing and keep going. If our fd was written to or a timeout // was received then we break out of the loop and return from this // call. let mut map = self.map.lock().unwrap(); if drain(&self.read) { self.process_sigchlds(&mut map); } if drain(&read) || timeout { break } } let mut map = self.map.lock().unwrap(); let (_write, ret) = map.remove(&id).unwrap(); Ok(ret) } fn process_sigchlds(&self, map: &mut StateMap) { for (&k, &mut (ref write, ref mut status)) in map { // Already reaped, nothing to do here if status.is_some() { continue } *status = try_wait(k).unwrap(); if status.is_some() { notify(write); } } } } fn file_pair() -> io::Result<(File, File)> { // TODO: CLOEXEC unsafe { let mut pipes = [0; 2]; if libc::pipe(pipes.as_mut_ptr()) != 0 { return Err(io::Error::last_os_error()) } let set = 1 as c_int; assert_eq!(libc::ioctl(pipes[0], libc::FIONBIO, &set), 0); assert_eq!(libc::ioctl(pipes[1], libc::FIONBIO, &set), 0); Ok((File::from_raw_fd(pipes[0]), File::from_raw_fd(pipes[1]))) } } fn try_wait(id: c_int) -> io::Result> { let mut status = 0; match unsafe { libc::waitpid(id, &mut status, libc::WNOHANG) } { 0 => Ok(None), n if n < 0 => return Err(io::Error::last_os_error()), n => { assert_eq!(n, id); Ok(Some(ExitStatus(status))) } } } fn drain(mut file: &File) -> bool { let mut ret = false; let mut buf = [0u8; 16]; loop { match file.read(&mut buf) { Ok(0) => return true, // EOF == something happened Ok(..) => ret = true, // data read, but keep draining Err(e) => { if e.kind() == io::ErrorKind::WouldBlock { return ret } else { panic!("bad read: {}", e) } } } } } fn notify(mut file: &File) { match file.write(&[1]) { Ok(..) => {} Err(e) => { if e.kind() != io::ErrorKind::WouldBlock { panic!("bad error on write fd: {}", e) } } } } fn now_ns() -> u64 { unsafe { let mut now: libc::timeval = mem::zeroed(); libc::gettimeofday(&mut now, 0 as *mut _); (now.tv_sec as u64 * 1_000_000_000) + (now.tv_usec as u64 * 1_000) } } // Signal handler for SIGCHLD signals, must be async-signal-safe! // // This function will write to the writing half of the "self pipe" to wake // up the helper thread if it's waiting. Note that this write must be // nonblocking because if it blocks and the reader is the thread we // interrupted, then we'll deadlock. // // When writing, if the write returns EWOULDBLOCK then we choose to ignore // it. At that point we're guaranteed that there's something in the pipe // which will wake up the other end at some point, so we just allow this // signal to be coalesced with the pending signals on the pipe. #[allow(unused_assignments)] extern fn sigchld_handler(signum: c_int, info: *mut libc::siginfo_t, ptr: *mut libc::c_void) { type FnSigaction = extern fn(c_int, *mut libc::siginfo_t, *mut libc::c_void); type FnHandler = extern fn(c_int); unsafe { let state = &*STATE; notify(&state.write); let fnptr = state.prev.sa_sigaction; if fnptr == 0 { return } // FIXME: remove this workaround when the PR to libc get merged and released // // This is a workaround for the type mismatch in the definition of SA_* // constants for android. See https://github.com/rust-lang/libc/pull/511 // if state.prev.sa_flags & _as!(libc::SA_SIGINFO, state.prev.sa_flags) == 0 { let action = mem::transmute::(fnptr); action(signum) } else { let action = mem::transmute::(fnptr); action(signum, info, ptr) } } } impl ExitStatus { pub fn success(&self) -> bool { self.code() == Some(0) } pub fn code(&self) -> Option { unsafe { if libc::WIFEXITED(self.0) { Some(libc::WEXITSTATUS(self.0)) } else { None } } } pub fn unix_signal(&self) -> Option { unsafe { if !libc::WIFEXITED(self.0) { Some(libc::WTERMSIG(self.0)) } else { None } } } } wait-timeout-0.1.5/src/windows.rs01006640001750000175000000003115126623714600015226 0ustar0000000000000000use std::io; use std::os::windows::prelude::*; use std::process::Child; use std::time::Duration; type DWORD = u32; type HANDLE = *mut u8; type BOOL = i32; type LPDWORD = *mut DWORD; const FALSE: BOOL = 0; const WAIT_OBJECT_0: DWORD = 0x00000000; const WAIT_TIMEOUT: DWORD = 258; extern "system" { fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD; fn GetExitCodeProcess(hProcess: HANDLE, lpExitCode: LPDWORD) -> BOOL; } #[derive(Eq, PartialEq, Copy, Clone, Debug)] pub struct ExitStatus(DWORD); pub fn wait_timeout(child: &mut Child, dur: Duration) -> io::Result> { let ms = dur.as_secs().checked_mul(1000).and_then(|amt| { amt.checked_add((dur.subsec_nanos() / 1_000_000) as u64) }).expect("failed to convert duration to milliseconds"); let ms = if ms > (DWORD::max_value() as u64) { DWORD::max_value() } else { ms as DWORD }; unsafe { match WaitForSingleObject(child.as_raw_handle() as *mut _, ms) { WAIT_OBJECT_0 => {} WAIT_TIMEOUT => return Ok(None), _ => return Err(io::Error::last_os_error()), } let mut status = 0; if GetExitCodeProcess(child.as_raw_handle() as *mut _, &mut status) == FALSE { Err(io::Error::last_os_error()) } else { Ok(Some(ExitStatus(status))) } } } impl ExitStatus { pub fn success(&self) -> bool { self.code() == Some(0) } pub fn code(&self) -> Option { Some(self.0 as i32) } pub fn unix_signal(&self) -> Option { None } } wait-timeout-0.1.5/tests/smoke.rs01006640001750000175000000004064130141045420015214 0ustar0000000000000000extern crate wait_timeout; use std::env; use std::process::{Command, Child}; use std::time::{Duration, Instant}; use wait_timeout::ChildExt; macro_rules! t { ($e:expr) => (match $e { Ok(e) => e, Err(e) => panic!("{} failed with {}", stringify!($e), e), }) } fn sleeper(ms: u32) -> Child { let mut me = env::current_exe().unwrap(); me.pop(); if me.ends_with("deps") { me.pop(); } me.push("sleep"); t!(Command::new(me).arg(ms.to_string()).spawn()) } fn exit(code: u32) -> Child { let mut me = env::current_exe().unwrap(); me.pop(); if me.ends_with("deps") { me.pop(); } me.push("exit"); t!(Command::new(me).arg(code.to_string()).spawn()) } #[test] fn smoke_insta_timeout() { let mut child = sleeper(1_000); assert_eq!(t!(child.wait_timeout_ms(0)), None); t!(child.kill()); let status = t!(child.wait()); assert!(!status.success()); } #[test] fn smoke_success() { let start = Instant::now(); let mut child = sleeper(0); let status = t!(child.wait_timeout_ms(1_000)).expect("should have succeeded"); assert!(status.success()); assert!(start.elapsed() < Duration::from_millis(500)); } #[test] fn smoke_timeout() { let mut child = sleeper(1_000_000); let start = Instant::now(); assert_eq!(t!(child.wait_timeout_ms(100)), None); assert!(start.elapsed() > Duration::from_millis(80)); t!(child.kill()); let status = t!(child.wait()); assert!(!status.success()); } #[test] fn exit_codes() { let mut child = exit(0); let status = t!(child.wait_timeout_ms(1_000)).unwrap(); assert_eq!(status.code(), Some(0)); let mut child = exit(1); let status = t!(child.wait_timeout_ms(1_000)).unwrap(); assert_eq!(status.code(), Some(1)); // check STILL_ACTIVE on windows, on unix this ends up just getting // truncated so don't bother with it. if cfg!(windows) { let mut child = exit(259); let status = t!(child.wait_timeout_ms(1_000)).unwrap(); assert_eq!(status.code(), Some(259)); } }