├── .github ├── dependabot.yml └── workflows │ └── main.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── src ├── bin │ ├── exit.rs │ ├── reader.rs │ └── sleep.rs ├── lib.rs ├── unix.rs └── windows.rs └── tests └── smoke.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: cargo 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "08:00" 8 | open-pull-requests-limit: 10 9 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: [push, pull_request] 3 | 4 | jobs: 5 | test: 6 | name: Test 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | matrix: 10 | include: 11 | - os: ubuntu-latest 12 | rust: stable 13 | - os: ubuntu-latest 14 | rust: beta 15 | - os: ubuntu-latest 16 | rust: nightly 17 | - os: windows-latest 18 | rust: stable 19 | - os: macos-latest 20 | rust: stable 21 | steps: 22 | - uses: actions/checkout@v2 23 | - name: Install Rust 24 | run: rustup update ${{ matrix.rust }} --no-self-update && rustup default ${{ matrix.rust }} 25 | shell: bash 26 | - run: cargo test 27 | 28 | rustfmt: 29 | name: Rustfmt 30 | runs-on: ubuntu-latest 31 | steps: 32 | - uses: actions/checkout@master 33 | - name: Install Rust 34 | run: rustup update stable && rustup default stable && rustup component add rustfmt 35 | - run: cargo fmt -- --check 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "wait-timeout" 3 | version = "0.2.1" 4 | authors = ["Alex Crichton "] 5 | license = "MIT/Apache-2.0" 6 | readme = "README.md" 7 | repository = "https://github.com/alexcrichton/wait-timeout" 8 | homepage = "https://github.com/alexcrichton/wait-timeout" 9 | documentation = "https://docs.rs/wait-timeout" 10 | description = """ 11 | A crate to wait on a child process with a timeout specified across Unix and 12 | Windows platforms. 13 | """ 14 | categories = ["os"] 15 | edition = '2021' 16 | 17 | [badges] 18 | travis-ci = { repository = "alexcrichton/wait-timeout" } 19 | appveyor = { repository = "alexcrichton/wait-timeout" } 20 | 21 | [target.'cfg(unix)'.dependencies] 22 | libc = "0.2.56" 23 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2014 Alex Crichton 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # wait-timeout 2 | 3 | [![Build Status](https://github.com/alexcrichton/wait-timeout/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/alexcrichton/wait-timeout/actions/workflows/main.yml) 4 | 5 | [Documentation](https://docs.rs/wait-timeout) 6 | 7 | Rust crate for waiting on a `Child` process with a timeout specified. 8 | 9 | ```sh 10 | $ cargo add wait-timeout 11 | ``` 12 | 13 | Example: 14 | 15 | ```rust 16 | use std::io; 17 | use std::process::Command; 18 | use std::time::{Duration, Instant}; 19 | use wait_timeout::ChildExt; 20 | 21 | fn main() -> io::Result<()> { 22 | let mut child = Command::new("sleep").arg("100").spawn()?; 23 | 24 | let start = Instant::now(); 25 | assert!(child.wait_timeout(Duration::from_millis(100))?.is_none()); 26 | assert!(start.elapsed() > Duration::from_millis(100)); 27 | 28 | child.kill()?; 29 | 30 | let start = Instant::now(); 31 | assert!(child.wait_timeout(Duration::from_millis(100))?.is_some()); 32 | assert!(start.elapsed() < Duration::from_millis(100)); 33 | 34 | Ok(()) 35 | } 36 | ``` 37 | -------------------------------------------------------------------------------- /src/bin/exit.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let code = std::env::args().nth(1).unwrap().parse().unwrap(); 3 | std::process::exit(code); 4 | } 5 | -------------------------------------------------------------------------------- /src/bin/reader.rs: -------------------------------------------------------------------------------- 1 | use std::io::{stdin, Read}; 2 | 3 | fn main() { 4 | let mut buffer: [u8; 32] = Default::default(); 5 | println!("about to block"); 6 | let _ = stdin().read(&mut buffer); 7 | } 8 | -------------------------------------------------------------------------------- /src/bin/sleep.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let amt = std::env::args().nth(1).unwrap().parse().unwrap(); 3 | std::thread::sleep(std::time::Duration::from_millis(amt)); 4 | } 5 | -------------------------------------------------------------------------------- /src/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 | use std::io; 35 | use std::process::{Child, ExitStatus}; 36 | use std::time::Duration; 37 | 38 | #[cfg(unix)] 39 | #[path = "unix.rs"] 40 | mod imp; 41 | #[cfg(windows)] 42 | #[path = "windows.rs"] 43 | mod imp; 44 | 45 | /// Extension methods for the standard [`std::process::Child`] type. 46 | pub trait ChildExt { 47 | /// Deprecated, use [`ChildExt::wait_timeout`] instead. 48 | #[doc(hidden)] 49 | fn wait_timeout_ms(&mut self, ms: u32) -> io::Result> { 50 | self.wait_timeout(Duration::from_millis(ms as u64)) 51 | } 52 | 53 | /// Wait for this child to exit, timing out after the duration `dur` has 54 | /// elapsed. 55 | /// 56 | /// If `Ok(None)` is returned then the timeout period elapsed without the 57 | /// child exiting, and if `Ok(Some(..))` is returned then the child exited 58 | /// with the specified exit code. 59 | fn wait_timeout(&mut self, dur: Duration) -> io::Result>; 60 | } 61 | 62 | impl ChildExt for Child { 63 | fn wait_timeout(&mut self, dur: Duration) -> io::Result> { 64 | drop(self.stdin.take()); 65 | imp::wait_timeout(self, dur) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/unix.rs: -------------------------------------------------------------------------------- 1 | //! Unix implementation of waiting for children with timeouts 2 | //! 3 | //! On unix, wait() and its friends have no timeout parameters, so there is 4 | //! no way to time out a thread in wait(). From some googling and some 5 | //! thinking, it appears that there are a few ways to handle timeouts in 6 | //! wait(), but the only real reasonable one for a multi-threaded program is 7 | //! to listen for SIGCHLD. 8 | //! 9 | //! With this in mind, the waiting mechanism with a timeout only uses 10 | //! waitpid() with WNOHANG, but otherwise all the necessary blocking is done by 11 | //! waiting for a SIGCHLD to arrive (and that blocking has a timeout). Note, 12 | //! however, that waitpid() is still used to actually reap the child. 13 | //! 14 | //! Signal handling is super tricky in general, and this is no exception. Due 15 | //! to the async nature of SIGCHLD, we use the self-pipe trick to transmit 16 | //! data out of the signal handler to the rest of the application. 17 | 18 | use libc::c_int; 19 | use std::collections::HashMap; 20 | use std::io::{self, Read, Write}; 21 | use std::mem; 22 | use std::os::unix::net::UnixStream; 23 | use std::os::unix::prelude::*; 24 | use std::process::{Child, ExitStatus}; 25 | use std::sync::{Mutex, Once}; 26 | use std::time::{Duration, Instant}; 27 | 28 | static INIT: Once = Once::new(); 29 | static mut STATE: *mut State = 0 as *mut _; 30 | 31 | struct State { 32 | prev: libc::sigaction, 33 | write: UnixStream, 34 | read: UnixStream, 35 | map: Mutex, 36 | } 37 | 38 | type StateMap = HashMap<*mut Child, (UnixStream, Option)>; 39 | 40 | pub fn wait_timeout(child: &mut Child, dur: Duration) -> io::Result> { 41 | INIT.call_once(State::init); 42 | unsafe { (*STATE).wait_timeout(child, dur) } 43 | } 44 | 45 | impl State { 46 | fn init() { 47 | unsafe { 48 | // Create our "self pipe" and then set both ends to nonblocking 49 | // mode. 50 | let (read, write) = UnixStream::pair().unwrap(); 51 | read.set_nonblocking(true).unwrap(); 52 | write.set_nonblocking(true).unwrap(); 53 | 54 | let state = Box::new(State { 55 | prev: mem::zeroed(), 56 | write: write, 57 | read: read, 58 | map: Mutex::new(HashMap::new()), 59 | }); 60 | 61 | // Register our sigchld handler 62 | let mut new: libc::sigaction = mem::zeroed(); 63 | new.sa_sigaction = sigchld_handler as usize; 64 | new.sa_flags = libc::SA_NOCLDSTOP | libc::SA_RESTART | libc::SA_SIGINFO; 65 | 66 | STATE = Box::into_raw(state); 67 | 68 | assert_eq!(libc::sigaction(libc::SIGCHLD, &new, &mut (*STATE).prev), 0); 69 | } 70 | } 71 | 72 | fn wait_timeout(&self, child: &mut Child, dur: Duration) -> io::Result> { 73 | // First up, prep our notification pipe which will tell us when our 74 | // child has been reaped (other threads may signal this pipe). 75 | let (read, write) = UnixStream::pair()?; 76 | read.set_nonblocking(true)?; 77 | write.set_nonblocking(true)?; 78 | 79 | // Next, take a lock on the map of children currently waiting. Right 80 | // after this, **before** we add ourselves to the map, we check to see 81 | // if our child has actually already exited via a `try_wait`. If the 82 | // child has exited then we return immediately as we'll never otherwise 83 | // receive a SIGCHLD notification. 84 | // 85 | // If the wait reports the child is still running, however, we add 86 | // ourselves to the map and then block in `select` waiting for something 87 | // to happen. 88 | let mut map = self.map.lock().unwrap(); 89 | if let Some(status) = child.try_wait()? { 90 | return Ok(Some(status)); 91 | } 92 | // Accessing a &mut reference invalidates any *mut pointers obtained from that reference. 93 | // Shadow the reference to make sure we don't touch it again. 94 | let child: *mut Child = child; 95 | assert!(map.insert(child, (write, None)).is_none()); 96 | drop(map); 97 | 98 | // Make sure that no matter what when we exit our pointer is removed 99 | // from the map. 100 | struct Remove<'a> { 101 | state: &'a State, 102 | child: *mut Child, 103 | } 104 | impl<'a> Drop for Remove<'a> { 105 | fn drop(&mut self) { 106 | let mut map = self.state.map.lock().unwrap(); 107 | drop(map.remove(&self.child)); 108 | } 109 | } 110 | let remove = Remove { state: self, child }; 111 | 112 | // Alright, we're guaranteed that we'll eventually get a SIGCHLD due 113 | // to our `try_wait` failing, and we're also guaranteed that we'll 114 | // get notified about this because we're in the map. Next up wait 115 | // for an event. 116 | // 117 | // Note that this happens in a loop for two reasons; we could 118 | // receive EINTR or we could pick up a SIGCHLD for other threads but not 119 | // actually be ready oureslves. 120 | let start = Instant::now(); 121 | let mut fds = [ 122 | libc::pollfd { 123 | fd: self.read.as_raw_fd(), 124 | events: libc::POLLIN, 125 | 126 | revents: 0, 127 | }, 128 | libc::pollfd { 129 | fd: read.as_raw_fd(), 130 | events: libc::POLLIN, 131 | revents: 0, 132 | }, 133 | ]; 134 | loop { 135 | let elapsed = start.elapsed(); 136 | if elapsed >= dur { 137 | break; 138 | } 139 | let timeout = dur - elapsed; 140 | let timeout = timeout 141 | .as_secs() 142 | .checked_mul(1_000) 143 | .and_then(|amt| amt.checked_add(timeout.subsec_nanos() as u64 / 1_000_000)) 144 | .unwrap_or(u64::MAX); 145 | let timeout = c_int::try_from(timeout).unwrap_or(c_int::MAX); 146 | let r = unsafe { libc::poll(fds.as_mut_ptr(), 2, timeout) }; 147 | let timeout = match r { 148 | 0 => true, 149 | n if n > 0 => false, 150 | n => { 151 | let err = io::Error::last_os_error(); 152 | if err.kind() == io::ErrorKind::Interrupted { 153 | continue; 154 | } else { 155 | panic!("error in select = {}: {}", n, err) 156 | } 157 | } 158 | }; 159 | 160 | // Now that something has happened, we need to process what actually 161 | // happened. There's are three reasons we could have woken up: 162 | // 163 | // 1. The file descriptor in our SIGCHLD handler was written to. 164 | // This means that a SIGCHLD was received and we need to poll the 165 | // entire list of waiting processes to figure out which ones 166 | // actually exited. 167 | // 2. Our file descriptor was written to. This means that another 168 | // thread reaped our child and listed the exit status in the 169 | // local map. 170 | // 3. We timed out. This means we need to remove ourselves from the 171 | // map and simply carry on. 172 | // 173 | // In the case that a SIGCHLD signal was received, we do that 174 | // processing and keep going. If our fd was written to or a timeout 175 | // was received then we break out of the loop and return from this 176 | // call. 177 | let mut map = self.map.lock().unwrap(); 178 | if drain(&self.read) { 179 | self.process_sigchlds(&mut map); 180 | } 181 | 182 | if drain(&read) || timeout { 183 | break; 184 | } 185 | } 186 | 187 | let mut map = self.map.lock().unwrap(); 188 | let (_write, ret) = map.remove(&(remove.child as *mut Child)).unwrap(); 189 | drop(map); 190 | Ok(ret) 191 | } 192 | 193 | fn process_sigchlds(&self, map: &mut StateMap) { 194 | for (k, (write, status)) in map { 195 | // Already reaped, nothing to do here 196 | if status.is_some() { 197 | continue; 198 | } 199 | 200 | *status = unsafe { (**k).try_wait().unwrap() }; 201 | if status.is_some() { 202 | notify(write); 203 | } 204 | } 205 | } 206 | } 207 | 208 | fn drain(mut file: &UnixStream) -> bool { 209 | let mut ret = false; 210 | let mut buf = [0u8; 16]; 211 | loop { 212 | match file.read(&mut buf) { 213 | Ok(0) => return true, // EOF == something happened 214 | Ok(..) => ret = true, // data read, but keep draining 215 | Err(e) => { 216 | if e.kind() == io::ErrorKind::WouldBlock { 217 | return ret; 218 | } else { 219 | panic!("bad read: {}", e) 220 | } 221 | } 222 | } 223 | } 224 | } 225 | 226 | fn notify(mut file: &UnixStream) { 227 | match file.write(&[1]) { 228 | Ok(..) => {} 229 | Err(e) => { 230 | if e.kind() != io::ErrorKind::WouldBlock { 231 | panic!("bad error on write fd: {}", e) 232 | } 233 | } 234 | } 235 | } 236 | 237 | // Signal handler for SIGCHLD signals, must be async-signal-safe! 238 | // 239 | // This function will write to the writing half of the "self pipe" to wake 240 | // up the helper thread if it's waiting. Note that this write must be 241 | // nonblocking because if it blocks and the reader is the thread we 242 | // interrupted, then we'll deadlock. 243 | // 244 | // When writing, if the write returns EWOULDBLOCK then we choose to ignore 245 | // it. At that point we're guaranteed that there's something in the pipe 246 | // which will wake up the other end at some point, so we just allow this 247 | // signal to be coalesced with the pending signals on the pipe. 248 | extern "C" fn sigchld_handler(signum: c_int, info: *mut libc::siginfo_t, ptr: *mut libc::c_void) { 249 | type FnSigaction = extern "C" fn(c_int, *mut libc::siginfo_t, *mut libc::c_void); 250 | type FnHandler = extern "C" fn(c_int); 251 | 252 | unsafe { 253 | let state = &*STATE; 254 | notify(&state.write); 255 | 256 | let fnptr = state.prev.sa_sigaction; 257 | if fnptr == 0 { 258 | return; 259 | } 260 | if state.prev.sa_flags & libc::SA_SIGINFO == 0 { 261 | let action = mem::transmute::(fnptr); 262 | action(signum) 263 | } else { 264 | let action = mem::transmute::(fnptr); 265 | action(signum, info, ptr) 266 | } 267 | } 268 | } 269 | -------------------------------------------------------------------------------- /src/windows.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::os::windows::prelude::*; 3 | use std::process::{Child, ExitStatus}; 4 | use std::time::{Duration, Instant}; 5 | 6 | type DWORD = u32; 7 | type HANDLE = *mut u8; 8 | 9 | const WAIT_OBJECT_0: DWORD = 0x00000000; 10 | const WAIT_TIMEOUT: DWORD = 258; 11 | 12 | extern "system" { 13 | fn WaitForSingleObject(hHandle: HANDLE, dwMilliseconds: DWORD) -> DWORD; 14 | } 15 | 16 | pub fn wait_timeout(child: &mut Child, dur: Duration) -> io::Result> { 17 | let start = Instant::now(); 18 | loop { 19 | let elapsed = start.elapsed(); 20 | if elapsed >= dur { 21 | return Ok(None); 22 | } 23 | let timeout = dur - elapsed; 24 | let ms = timeout.as_millis(); 25 | let ms = DWORD::try_from(ms).unwrap_or(DWORD::MAX); 26 | unsafe { 27 | match WaitForSingleObject(child.as_raw_handle().cast(), ms) { 28 | WAIT_OBJECT_0 => {} 29 | WAIT_TIMEOUT => return Ok(None), 30 | _ => return Err(io::Error::last_os_error()), 31 | } 32 | } 33 | return child.try_wait(); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /tests/smoke.rs: -------------------------------------------------------------------------------- 1 | use std::env; 2 | use std::io::Read; 3 | use std::process::{Child, Command, Stdio}; 4 | use std::time::{Duration, Instant}; 5 | 6 | use wait_timeout::ChildExt; 7 | 8 | fn sleeper(ms: u32) -> Child { 9 | let mut me = env::current_exe().unwrap(); 10 | me.pop(); 11 | if me.ends_with("deps") { 12 | me.pop(); 13 | } 14 | me.push("sleep"); 15 | Command::new(me).arg(ms.to_string()).spawn().unwrap() 16 | } 17 | 18 | fn exit(code: u32) -> Child { 19 | let mut me = env::current_exe().unwrap(); 20 | me.pop(); 21 | if me.ends_with("deps") { 22 | me.pop(); 23 | } 24 | me.push("exit"); 25 | Command::new(me).arg(code.to_string()).spawn().unwrap() 26 | } 27 | 28 | fn reader() -> Child { 29 | let mut me = env::current_exe().unwrap(); 30 | me.pop(); 31 | if me.ends_with("deps") { 32 | me.pop(); 33 | } 34 | me.push("reader"); 35 | Command::new(me) 36 | .stdin(Stdio::piped()) 37 | .stdout(Stdio::piped()) 38 | .spawn() 39 | .unwrap() 40 | } 41 | 42 | #[test] 43 | fn smoke_insta_timeout() { 44 | let mut child = sleeper(1_000); 45 | assert_eq!(child.wait_timeout_ms(0).unwrap(), None); 46 | 47 | child.kill().unwrap(); 48 | let status = child.wait().unwrap(); 49 | assert!(!status.success()); 50 | } 51 | 52 | #[test] 53 | fn smoke_success() { 54 | let start = Instant::now(); 55 | let mut child = sleeper(0); 56 | let status = child 57 | .wait_timeout_ms(1_000) 58 | .unwrap() 59 | .expect("should have succeeded"); 60 | assert!(status.success()); 61 | 62 | assert!(start.elapsed() < Duration::from_millis(500)); 63 | } 64 | 65 | #[test] 66 | fn smoke_timeout() { 67 | let mut child = sleeper(1_000_000); 68 | let start = Instant::now(); 69 | assert_eq!(child.wait_timeout_ms(100).unwrap(), None); 70 | assert!(start.elapsed() > Duration::from_millis(80)); 71 | 72 | child.kill().unwrap(); 73 | let status = child.wait().unwrap(); 74 | assert!(!status.success()); 75 | } 76 | 77 | #[test] 78 | fn smoke_reader() { 79 | let mut child = reader(); 80 | 81 | // wait for the child to start and print something 82 | let mut buf = [0; 20]; 83 | let _ = child.stdout.take().unwrap().read(&mut buf); 84 | 85 | let dur = Duration::from_millis(100); 86 | let status = child.wait_timeout(dur).unwrap().unwrap(); 87 | assert!(status.success()); 88 | } 89 | 90 | #[test] 91 | fn exit_codes() { 92 | let mut child = exit(0); 93 | let status = child.wait_timeout_ms(1_000).unwrap().unwrap(); 94 | assert_eq!(status.code(), Some(0)); 95 | 96 | let mut child = exit(1); 97 | let status = child.wait_timeout_ms(1_000).unwrap().unwrap(); 98 | assert_eq!(status.code(), Some(1)); 99 | 100 | // check STILL_ACTIVE on windows, on unix this ends up just getting 101 | // truncated so don't bother with it. 102 | if cfg!(windows) { 103 | let mut child = exit(259); 104 | let status = child.wait_timeout_ms(1_000).unwrap().unwrap(); 105 | assert_eq!(status.code(), Some(259)); 106 | } 107 | } 108 | --------------------------------------------------------------------------------