| 1 |
//! A library for awaiting and killing child processes from multiple threads. |
| 2 |
//! |
| 3 |
//! - [Docs](https://docs.rs/shared_child) |
| 4 |
//! - [Crate](https://crates.io/crates/shared_child) |
| 5 |
//! - [Repo](https://github.com/oconnor663/shared_child.rs) |
| 6 |
//! |
| 7 |
//! The |
| 8 |
//! [`std::process::Child`](https://doc.rust-lang.org/std/process/struct.Child.html) |
| 9 |
//! type in the standard library provides |
| 10 |
//! [`wait`](https://doc.rust-lang.org/std/process/struct.Child.html#method.wait) |
| 11 |
//! and |
| 12 |
//! [`kill`](https://doc.rust-lang.org/std/process/struct.Child.html#method.kill) |
| 13 |
//! methods that take `&mut self`, making it impossible to kill a child process |
| 14 |
//! while another thread is waiting on it. That design works around a race |
| 15 |
//! condition in Unix's `waitpid` function, where a PID might get reused as soon |
| 16 |
//! as the wait returns, so a signal sent around the same time could |
| 17 |
//! accidentally get delivered to the wrong process. |
| 18 |
//! |
| 19 |
//! However with the newer POSIX `waitid` function, we can wait on a child |
| 20 |
//! without freeing its PID for reuse. That makes it safe to send signals |
| 21 |
//! concurrently. Windows has actually always supported this, by preventing PID |
| 22 |
//! reuse while there are still open handles to a child process. This library |
| 23 |
//! wraps `std::process::Child` for concurrent use, backed by these APIs. |
| 24 |
//! |
| 25 |
//! Compatibility note: The `libc` crate doesn't currently support `waitid` on |
| 26 |
//! NetBSD or OpenBSD, or on older versions of OSX. There [might also |
| 27 |
//! be](https://bugs.python.org/msg167016) some version of OSX where the |
| 28 |
//! `waitid` function exists but is broken. We can add a "best effort" |
| 29 |
//! workaround using `waitpid` for these platforms as we run into them. Please |
| 30 |
//! [file an issue](https://github.com/oconnor663/shared_child.rs/issues/new) if |
| 31 |
//! you hit this. |
| 32 |
//! |
| 33 |
//! # Example |
| 34 |
//! |
| 35 |
//! ```rust |
| 36 |
//! use shared_child::SharedChild; |
| 37 |
//! use std::process::Command; |
| 38 |
//! use std::sync::Arc; |
| 39 |
//! |
| 40 |
//! // Spawn a child that will just sleep for a long time, |
| 41 |
//! // and put it in an Arc to share between threads. |
| 42 |
//! let mut command = Command::new("python"); |
| 43 |
//! command.arg("-c").arg("import time; time.sleep(1000000000)"); |
| 44 |
//! let shared_child = SharedChild::spawn(&mut command).unwrap(); |
| 45 |
//! let child_arc = Arc::new(shared_child); |
| 46 |
//! |
| 47 |
//! // On another thread, wait on the child process. |
| 48 |
//! let child_arc_clone = child_arc.clone(); |
| 49 |
//! let thread = std::thread::spawn(move || { |
| 50 |
//! child_arc_clone.wait().unwrap() |
| 51 |
//! }); |
| 52 |
//! |
| 53 |
//! // While the other thread is waiting, kill the child process. |
| 54 |
//! // This wouldn't be possible with e.g. Arc<Mutex<Child>> from |
| 55 |
//! // the standard library, because the waiting thread would be |
| 56 |
//! // holding the mutex. |
| 57 |
//! child_arc.kill().unwrap(); |
| 58 |
//! |
| 59 |
//! // Join the waiting thread and get the exit status. |
| 60 |
//! let exit_status = thread.join().unwrap(); |
| 61 |
//! assert!(!exit_status.success()); |
| 62 |
//! ``` |
| 63 |
|
| 64 |
use std::io; |
| 65 |
use std::process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus}; |
| 66 |
use std::sync::{Condvar, Mutex, MutexGuard}; |
| 67 |
#[cfg(feature = "timeout")] |
| 68 |
use std::time::{Duration, Instant}; |
| 69 |
|
| 70 |
mod sys; |
| 71 |
|
| 72 |
// Publish the Unix-only SharedChildExt trait. |
| 73 |
#[cfg(unix)] |
| 74 |
pub mod unix; |
| 75 |
|
| 76 |
#[derive(Debug)] |
| 77 |
enum ChildState { |
| 78 |
NotWaiting, |
| 79 |
Waiting, |
| 80 |
Exited(ExitStatus), |
| 81 |
} |
| 82 |
|
| 83 |
use crate::ChildState::{Exited, NotWaiting, Waiting}; |
| 84 |
|
| 85 |
#[derive(Debug)] |
| 86 |
struct SharedChildInner { |
| 87 |
child: Child, |
| 88 |
state: ChildState, |
| 89 |
} |
| 90 |
|
| 91 |
#[derive(Debug)] |
| 92 |
pub struct SharedChild { |
| 93 |
inner: Mutex<SharedChildInner>, |
| 94 |
condvar: Condvar, |
| 95 |
} |
| 96 |
|
| 97 |
impl SharedChild { |
| 98 |
/// Spawn a new `SharedChild` from a |
| 99 |
/// [`std::process::Command`](https://doc.rust-lang.org/std/process/struct.Command.html). |
| 100 |
pub fn spawn(command: &mut Command) -> io::Result<Self> { |
| 101 |
Ok(SharedChild { |
| 102 |
inner: Mutex::new(SharedChildInner { |
| 103 |
child: command.spawn()?, |
| 104 |
state: NotWaiting, |
| 105 |
}), |
| 106 |
condvar: Condvar::new(), |
| 107 |
}) |
| 108 |
} |
| 109 |
|
| 110 |
/// Construct a new `SharedChild` from an already spawned |
| 111 |
/// [`std::process::Child`](https://doc.rust-lang.org/std/process/struct.Child.html). |
| 112 |
/// |
| 113 |
/// This constructor needs to know whether `child` has already been waited on, and the only way |
| 114 |
/// to find that out is to call |
| 115 |
/// [`Child::try_wait`](https://doc.rust-lang.org/std/process/struct.Child.html#method.try_wait) |
| 116 |
/// internally. If the child process is currently a zombie, that call will clean it up as a |
| 117 |
/// side effect. The [`SharedChild::spawn`] constructor doesn't need to do this. |
| 118 |
pub fn new(mut child: Child) -> io::Result<Self> { |
| 119 |
let state = if let Some(exit_status) = child.try_wait()? { |
| 120 |
Exited(exit_status) |
| 121 |
} else { |
| 122 |
NotWaiting |
| 123 |
}; |
| 124 |
Ok(SharedChild { |
| 125 |
inner: Mutex::new(SharedChildInner { child, state }), |
| 126 |
condvar: Condvar::new(), |
| 127 |
}) |
| 128 |
} |
| 129 |
|
| 130 |
/// Return the child process ID. |
| 131 |
pub fn id(&self) -> u32 { |
| 132 |
self.inner.lock().unwrap().child.id() |
| 133 |
} |
| 134 |
|
| 135 |
/// Wait for the child to exit, blocking the current thread, and return its |
| 136 |
/// exit status. |
| 137 |
pub fn wait(&self) -> io::Result<ExitStatus> { |
| 138 |
// Start by taking the inner lock, but note that we need to release it before waiting, or |
| 139 |
// else we'd block .try_wait(), .wait_deadline(), and .kill(). |
| 140 |
let mut inner_guard = self.inner.lock().unwrap(); |
| 141 |
loop { |
| 142 |
match inner_guard.state { |
| 143 |
// The child has already been reaped. Return its saved exit status. |
| 144 |
Exited(exit_status) => return Ok(exit_status), |
| 145 |
// There is another blocking waiter. Sleep until it signals the condvar. Spurious |
| 146 |
// wakeups are acceptable here. |
| 147 |
Waiting => inner_guard = self.condvar.wait(inner_guard).unwrap(), |
| 148 |
// There are no other blocking waiters. Proceed to the blocking wait. |
| 149 |
NotWaiting => break, |
| 150 |
} |
| 151 |
} |
| 152 |
|
| 153 |
// We are the blocking waiter. Set the state to Waiting and release the lock before |
| 154 |
// blocking. After this, we must reset the state and notify the condvar before returning. |
| 155 |
inner_guard.state = Waiting; |
| 156 |
let handle = sys::get_handle(&inner_guard.child); |
| 157 |
drop(inner_guard); |
| 158 |
|
| 159 |
// Do the blocking wait. |
| 160 |
let wait_result = sys::wait_noreap(handle); |
| 161 |
|
| 162 |
// Before checking the result, reacquire the lock, leave the Waiting state, and notify the |
| 163 |
// condvar. If the child did exit, we'll set the Exited state before releasing the lock |
| 164 |
// again, and no other threads will observe NotWaiting. |
| 165 |
inner_guard = self.inner.lock().unwrap(); |
| 166 |
inner_guard.state = NotWaiting; |
| 167 |
self.condvar.notify_all(); |
| 168 |
|
| 169 |
wait_result?; |
| 170 |
// The child has exited. Reap it with std::process::Child::wait. The state was Waiting when |
| 171 |
// we re-acquired the lock, so there are no other threads in blocking waits (other waiters |
| 172 |
// would be sleeping on the condvar), and it's safe to free the child PID. |
| 173 |
let exit_status = inner_guard.child.wait()?; |
| 174 |
inner_guard.state = Exited(exit_status); |
| 175 |
Ok(exit_status) |
| 176 |
} |
| 177 |
|
| 178 |
/// Wait for the child to exit, blocking the current thread, and return its exit status. Or if |
| 179 |
/// the timeout passes before then, return `Ok(None)`. |
| 180 |
/// |
| 181 |
/// This polls the child at least once, and if the child has already exited it will return |
| 182 |
/// `Ok(Some(_))` even if the timeout is zero. |
| 183 |
#[cfg(feature = "timeout")] |
| 184 |
pub fn wait_timeout(&self, timeout: Duration) -> io::Result<Option<ExitStatus>> { |
| 185 |
let deadline = std::time::Instant::now() + timeout; |
| 186 |
self.wait_deadline(deadline) |
| 187 |
} |
| 188 |
|
| 189 |
/// Wait for the child to exit, blocking the current thread, and return its exit status. Or if |
| 190 |
/// the deadline passes before then, return `Ok(None)`. |
| 191 |
/// |
| 192 |
/// This polls the child at least once, and if the child has already exited it will return |
| 193 |
/// `Ok(Some(_))` even if the deadline is in the past. |
| 194 |
#[cfg(feature = "timeout")] |
| 195 |
pub fn wait_deadline(&self, deadline: Instant) -> io::Result<Option<ExitStatus>> { |
| 196 |
// Start by taking the inner lock, but note that we need to release it before waiting, or |
| 197 |
// else we'd block .try_wait(), .kill(), and other calls to .wait_deadline(). |
| 198 |
let mut inner_guard = self.inner.lock().unwrap(); |
| 199 |
loop { |
| 200 |
match inner_guard.state { |
| 201 |
// The child has already been reaped. Return its saved exit status. |
| 202 |
Exited(exit_status) => return Ok(Some(exit_status)), |
| 203 |
// The deadline has passed. Poll the child on the way out, to make sure we always |
| 204 |
// poll at least once. |
| 205 |
_ if deadline < Instant::now() => { |
| 206 |
return self.try_wait_inner(inner_guard); |
| 207 |
} |
| 208 |
// There is another blocking waiter. Sleep until it signals the condvar or the |
| 209 |
// deadline passes. Spurious wakeups are acceptable here. |
| 210 |
Waiting => { |
| 211 |
let timeout = deadline.saturating_duration_since(Instant::now()); |
| 212 |
inner_guard = self.condvar.wait_timeout(inner_guard, timeout).unwrap().0; |
| 213 |
} |
| 214 |
// There are no other blocking waiters. Proceed to the blocking wait. |
| 215 |
NotWaiting => break, |
| 216 |
} |
| 217 |
} |
| 218 |
|
| 219 |
// We are the blocking waiter. Set the state to Waiting and release the lock before |
| 220 |
// blocking. After this, we must reset the state and notify the condvar before returning. |
| 221 |
inner_guard.state = Waiting; |
| 222 |
let handle = sys::get_handle(&inner_guard.child); |
| 223 |
drop(inner_guard); |
| 224 |
|
| 225 |
// Do the blocking wait. |
| 226 |
let wait_result = sys::wait_deadline_noreap(handle, deadline); |
| 227 |
|
| 228 |
// Before checking the result, reacquire the lock, leave the Waiting state, and notify the |
| 229 |
// condvar. If the child did exit, we'll set the Exited state before releasing the lock |
| 230 |
// again, and no other threads will observe NotWaiting. |
| 231 |
inner_guard = self.inner.lock().unwrap(); |
| 232 |
inner_guard.state = NotWaiting; |
| 233 |
self.condvar.notify_all(); |
| 234 |
|
| 235 |
let exited = wait_result?; |
| 236 |
if exited { |
| 237 |
// The child has exited. Reap it with std::process::Child::wait. The state was Waiting |
| 238 |
// when we re-acquired the lock, so there are no other threads in blocking waits (other |
| 239 |
// waiters would be sleeping on the condvar), and it's safe to free the child PID. |
| 240 |
let exit_status = inner_guard.child.wait()?; |
| 241 |
inner_guard.state = Exited(exit_status); |
| 242 |
Ok(Some(exit_status)) |
| 243 |
} else { |
| 244 |
Ok(None) |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
/// Return the child's exit status if it has already exited. If the child is still running, |
| 249 |
/// return `Ok(None)`. |
| 250 |
pub fn try_wait(&self) -> io::Result<Option<ExitStatus>> { |
| 251 |
// Taking this lock will not block for long, because .wait() and .wait_deadline() don't |
| 252 |
// hold it while waiting. |
| 253 |
let inner_guard = self.inner.lock().unwrap(); |
| 254 |
self.try_wait_inner(inner_guard) |
| 255 |
} |
| 256 |
|
| 257 |
fn try_wait_inner( |
| 258 |
&self, |
| 259 |
mut inner_guard: MutexGuard<SharedChildInner>, |
| 260 |
) -> io::Result<Option<ExitStatus>> { |
| 261 |
match inner_guard.state { |
| 262 |
// The child has already been reaped. Return its saved exit status. |
| 263 |
Exited(exit_status) => Ok(Some(exit_status)), |
| 264 |
// There are no other blocking waiters, so it's safe to (potentially) reap the child |
| 265 |
// and free the child PID with std::process::Child::try_wait. |
| 266 |
NotWaiting => { |
| 267 |
if let Some(status) = inner_guard.child.try_wait()? { |
| 268 |
inner_guard.state = Exited(status); |
| 269 |
Ok(Some(status)) |
| 270 |
} else { |
| 271 |
Ok(None) |
| 272 |
} |
| 273 |
} |
| 274 |
// There is another blocking waiter, which might still be in libc::waitid. Poll the |
| 275 |
// child to see whether it's exited, without reaping it. This library used to take the |
| 276 |
// `Waiting` status as a proxy for "not exited yet", but we no longer do that for two |
| 277 |
// reasons: |
| 278 |
// 1. That risks a subtle race condition. If a wait()ing thread sets the Waiting status |
| 279 |
// and releases the child lock without first polling the child, a call to try_wait() |
| 280 |
// from another thread at the exact same time might incorrectly assume the child |
| 281 |
// hasn't exited yet, even if in fact it exited long ago. Polling before releasing |
| 282 |
// the lock avoids this, but it's easy to forget. Note that this is currently a bug |
| 283 |
// in the Python standard library: https://github.com/python/cpython/issues/127050 |
| 284 |
// 2. If try_wait() is racing against child exit, it's possible to have a case where |
| 285 |
// polling *would've* returned true, but we don't poll and instead return false. We |
| 286 |
// used to say we didn't care about that, because if you're racing exit then you |
| 287 |
// shouldn't really care answer you get. But that's not entirely fair, because you |
| 288 |
// might be calling try_wait() in response to receiving SIGCHLD, in which case you |
| 289 |
// *know* the child has exited. In that case you're not really racing against exit, |
| 290 |
// but only against the wait() thread. We prefer to guarantee that you'll get true |
| 291 |
// in that case. (It's arguably more robust to call wait() instead if you *know* the |
| 292 |
// child has exited, but either should work after SIGCHLD.) |
| 293 |
Waiting => { |
| 294 |
if sys::try_wait_noreap(sys::get_handle(&inner_guard.child))? { |
| 295 |
// The child has exited, but we can't reap it without conflicting with the |
| 296 |
// other waiter, so use `.wait()` instead to synchronize with it. |
| 297 |
drop(inner_guard); |
| 298 |
let exit_status = self.wait()?; |
| 299 |
Ok(Some(exit_status)) |
| 300 |
} else { |
| 301 |
Ok(None) |
| 302 |
} |
| 303 |
} |
| 304 |
} |
| 305 |
} |
| 306 |
|
| 307 |
/// Send a kill signal to the child. On Unix this sends SIGKILL, and you |
| 308 |
/// should call `wait` afterwards to avoid leaving a zombie. If the process |
| 309 |
/// has already been waited on, this returns `Ok(())` and does nothing. |
| 310 |
pub fn kill(&self) -> io::Result<()> { |
| 311 |
// The reason we can do this, but the standard library can't, is that on Unix our |
| 312 |
// SharedChild::wait function uses the newer (i.e. only 20 years old) libc::waitid with the |
| 313 |
// WNOWAIT flag, which lets it wait for the child to exit without reaping it. The actual |
| 314 |
// reaping happens after SharedChild::wait re-acquires the inner lock, which is the same |
| 315 |
// lock we take here, preventing the PID reuse race. |
| 316 |
// |
| 317 |
// Taking this lock won't block, because .wait() and .wait_deadline() don't hold it while |
| 318 |
// blocking. Also we always reap the child process via std::process::Child methods, so this |
| 319 |
// is a safe no-op after we've freed the child PID. |
| 320 |
self.inner.lock().unwrap().child.kill() |
| 321 |
} |
| 322 |
|
| 323 |
/// Consume the `SharedChild` and return the |
| 324 |
/// [`std::process::Child`](https://doc.rust-lang.org/std/process/struct.Child.html) it |
| 325 |
/// contains. |
| 326 |
/// |
| 327 |
/// We never reap the child process except by calling |
| 328 |
/// [`std::process::Child`](https://doc.rust-lang.org/std/process/struct.Child.html) methods on |
| 329 |
/// it, so the child object's inner state is correct, even if it was waited on while it was |
| 330 |
/// shared. |
| 331 |
pub fn into_inner(self) -> Child { |
| 332 |
self.inner.into_inner().unwrap().child |
| 333 |
} |
| 334 |
|
| 335 |
/// Take the child's |
| 336 |
/// [`stdin`](https://doc.rust-lang.org/std/process/struct.Child.html#structfield.stdin) |
| 337 |
/// handle, if any. |
| 338 |
/// |
| 339 |
/// This will only return `Some` the first time it's called, and then only if the `Command` |
| 340 |
/// that created the child was configured with `.stdin(Stdio::piped())`. |
| 341 |
pub fn take_stdin(&self) -> Option<ChildStdin> { |
| 342 |
self.inner.lock().unwrap().child.stdin.take() |
| 343 |
} |
| 344 |
|
| 345 |
/// Take the child's |
| 346 |
/// [`stdout`](https://doc.rust-lang.org/std/process/struct.Child.html#structfield.stdout) |
| 347 |
/// handle, if any. |
| 348 |
/// |
| 349 |
/// This will only return `Some` the first time it's called, and then only if the `Command` |
| 350 |
/// that created the child was configured with `.stdout(Stdio::piped())`. |
| 351 |
pub fn take_stdout(&self) -> Option<ChildStdout> { |
| 352 |
self.inner.lock().unwrap().child.stdout.take() |
| 353 |
} |
| 354 |
|
| 355 |
/// Take the child's |
| 356 |
/// [`stderr`](https://doc.rust-lang.org/std/process/struct.Child.html#structfield.stderr) |
| 357 |
/// handle, if any. |
| 358 |
/// |
| 359 |
/// This will only return `Some` the first time it's called, and then only if the `Command` |
| 360 |
/// that created the child was configured with `.stderr(Stdio::piped())`. |
| 361 |
pub fn take_stderr(&self) -> Option<ChildStderr> { |
| 362 |
self.inner.lock().unwrap().child.stderr.take() |
| 363 |
} |
| 364 |
} |
| 365 |
|
| 366 |
#[cfg(test)] |
| 367 |
mod tests { |
| 368 |
use super::*; |
| 369 |
use std::error::Error; |
| 370 |
use std::process::{Command, Stdio}; |
| 371 |
use std::sync::Arc; |
| 372 |
use std::time::{Duration, Instant}; |
| 373 |
|
| 374 |
// Python isn't available on some Unix platforms, e.g. Android, so we need this instead. |
| 375 |
#[cfg(unix)] |
| 376 |
pub fn true_cmd() -> Command { |
| 377 |
Command::new("true") |
| 378 |
} |
| 379 |
|
| 380 |
#[cfg(not(unix))] |
| 381 |
pub fn true_cmd() -> Command { |
| 382 |
let mut cmd = Command::new("python"); |
| 383 |
cmd.arg("-c").arg(""); |
| 384 |
cmd |
| 385 |
} |
| 386 |
|
| 387 |
// Python isn't available on some Unix platforms, e.g. Android, so we need this instead. |
| 388 |
#[cfg(unix)] |
| 389 |
pub fn sleep_cmd(duration: Duration) -> Command { |
| 390 |
let mut cmd = Command::new("sleep"); |
| 391 |
cmd.arg(format!("{}", duration.as_secs_f32())); |
| 392 |
cmd |
| 393 |
} |
| 394 |
|
| 395 |
#[cfg(not(unix))] |
| 396 |
pub fn sleep_cmd(duration: Duration) -> Command { |
| 397 |
let mut cmd = Command::new("python"); |
| 398 |
cmd.arg("-c").arg(format!( |
| 399 |
"import time; time.sleep({})", |
| 400 |
duration.as_secs_f32() |
| 401 |
)); |
| 402 |
cmd |
| 403 |
} |
| 404 |
|
| 405 |
pub fn sleep_forever_cmd() -> Command { |
| 406 |
sleep_cmd(Duration::from_secs(1000000)) |
| 407 |
} |
| 408 |
|
| 409 |
// Python isn't available on some Unix platforms, e.g. Android, so we need this instead. |
| 410 |
#[cfg(unix)] |
| 411 |
pub fn cat_cmd() -> Command { |
| 412 |
Command::new("cat") |
| 413 |
} |
| 414 |
|
| 415 |
#[cfg(not(unix))] |
| 416 |
pub fn cat_cmd() -> Command { |
| 417 |
let mut cmd = Command::new("python"); |
| 418 |
cmd.arg("-c").arg(""); |
| 419 |
cmd |
| 420 |
} |
| 421 |
|
| 422 |
#[test] |
| 423 |
fn test_wait() { |
| 424 |
let child = SharedChild::spawn(&mut true_cmd()).unwrap(); |
| 425 |
// Test the id() function while we're at it. |
| 426 |
let id = child.id(); |
| 427 |
assert!(id > 0); |
| 428 |
let status = child.wait().unwrap(); |
| 429 |
assert_eq!(status.code().unwrap(), 0); |
| 430 |
} |
| 431 |
|
| 432 |
#[cfg(feature = "timeout")] |
| 433 |
fn exited_but_unawaited_child() -> SharedChild { |
| 434 |
// The `true` command will exit immediately. |
| 435 |
let child = SharedChild::spawn(&mut true_cmd()).unwrap(); |
| 436 |
// Wait on the child "out of band", so the SharedChild state is not updated. |
| 437 |
let handle = sys::get_handle(&child.inner.lock().unwrap().child); |
| 438 |
sys::wait_noreap(handle).unwrap(); |
| 439 |
// At this point the child has definitely exited, but the SharedChild is still in the |
| 440 |
// NotWaiting state. |
| 441 |
child |
| 442 |
} |
| 443 |
|
| 444 |
// This test is pretty much copy-pasted as test_wait_deadline below. Copy-paste any future |
| 445 |
// changes too. |
| 446 |
#[test] |
| 447 |
#[cfg(feature = "timeout")] |
| 448 |
fn test_wait_timeout() { |
| 449 |
let exited_child = exited_but_unawaited_child(); |
| 450 |
// The first .wait_timeout reaps the child. |
| 451 |
assert!(exited_child |
| 452 |
.wait_timeout(Duration::from_secs(0)) |
| 453 |
.expect("no IO error") |
| 454 |
.expect("did not time out") |
| 455 |
.success()); |
| 456 |
// The second returns the cached status. |
| 457 |
assert!(exited_child |
| 458 |
.wait_timeout(Duration::from_secs(0)) |
| 459 |
.expect("no IO error") |
| 460 |
.expect("did not time out") |
| 461 |
.success()); |
| 462 |
|
| 463 |
// Test two different timeout cases. First, if we're the only waiter... |
| 464 |
let long_child = Arc::new(SharedChild::spawn(&mut sleep_forever_cmd()).unwrap()); |
| 465 |
let status = long_child |
| 466 |
.wait_timeout(Duration::from_millis(10)) |
| 467 |
.expect("no IO error"); |
| 468 |
assert!(status.is_none(), "timed out"); |
| 469 |
// And second, if there's another background thread already waiting (this tests the condvar |
| 470 |
// wait loop, which the first case skips)... |
| 471 |
let long_child_clone = Arc::clone(&long_child); |
| 472 |
std::thread::spawn(move || long_child_clone.wait().unwrap()); |
| 473 |
// There's no perfect way to make sure that the bg thread has already entered the blocking |
| 474 |
// wait, so just sleep for a moment before waiting. Weird timing here might mean we're not |
| 475 |
// testing what we meant to, but it won't make the test fail. |
| 476 |
std::thread::sleep(Duration::from_millis(10)); |
| 477 |
let status = long_child |
| 478 |
.wait_timeout(Duration::from_millis(10)) |
| 479 |
.expect("no IO error"); |
| 480 |
assert!(status.is_none(), "timed out"); |
| 481 |
|
| 482 |
// Kill and clean up the long_child, mostly just to avoid leaving processes around after |
| 483 |
// the test suite is finished. |
| 484 |
long_child.kill().unwrap(); |
| 485 |
long_child |
| 486 |
.wait_timeout(Duration::from_millis(100)) |
| 487 |
.expect("no IO error") |
| 488 |
.expect("did not time out"); |
| 489 |
} |
| 490 |
|
| 491 |
// This test is pretty much copy-pasted as test_wait_timeout above. Copy-paste any future |
| 492 |
// changes too. |
| 493 |
#[test] |
| 494 |
#[cfg(feature = "timeout")] |
| 495 |
fn test_wait_deadline() { |
| 496 |
let exited_child = exited_but_unawaited_child(); |
| 497 |
// The first .wait_deadline reaps the child. |
| 498 |
assert!(exited_child |
| 499 |
.wait_deadline(Instant::now() + Duration::from_secs(0)) |
| 500 |
.expect("no IO error") |
| 501 |
.expect("did not time out") |
| 502 |
.success()); |
| 503 |
// The second returns the cached status. |
| 504 |
assert!(exited_child |
| 505 |
.wait_deadline(Instant::now() + Duration::from_secs(0)) |
| 506 |
.expect("no IO error") |
| 507 |
.expect("did not time out") |
| 508 |
.success()); |
| 509 |
|
| 510 |
// Test two different timeout cases. First, if we're the only waiter... |
| 511 |
let long_child = Arc::new(SharedChild::spawn(&mut sleep_forever_cmd()).unwrap()); |
| 512 |
let status = long_child |
| 513 |
.wait_deadline(Instant::now() + Duration::from_millis(10)) |
| 514 |
.expect("no IO error"); |
| 515 |
assert!(status.is_none(), "timed out"); |
| 516 |
// And second, if there's another background thread already waiting (this tests the condvar |
| 517 |
// wait loop, which the first case skips)... |
| 518 |
let long_child_clone = Arc::clone(&long_child); |
| 519 |
std::thread::spawn(move || long_child_clone.wait().unwrap()); |
| 520 |
// There's no perfect way to make sure that the bg thread has already entered the blocking |
| 521 |
// wait, so just sleep for a moment before waiting. Weird timing here might mean we're not |
| 522 |
// testing what we meant to, but it won't make the test fail. |
| 523 |
std::thread::sleep(Duration::from_millis(10)); |
| 524 |
let status = long_child |
| 525 |
.wait_deadline(Instant::now() + Duration::from_millis(10)) |
| 526 |
.expect("no IO error"); |
| 527 |
assert!(status.is_none(), "timed out"); |
| 528 |
|
| 529 |
// Kill and clean up the long_child, mostly just to avoid leaving processes around after |
| 530 |
// the test suite is finished. |
| 531 |
long_child.kill().unwrap(); |
| 532 |
long_child |
| 533 |
.wait_deadline(Instant::now() + Duration::from_millis(100)) |
| 534 |
.expect("no IO error") |
| 535 |
.expect("did not time out"); |
| 536 |
} |
| 537 |
|
| 538 |
#[test] |
| 539 |
fn test_kill() { |
| 540 |
let child = SharedChild::spawn(&mut sleep_forever_cmd()).unwrap(); |
| 541 |
child.kill().unwrap(); |
| 542 |
let status = child.wait().unwrap(); |
| 543 |
assert!(!status.success()); |
| 544 |
} |
| 545 |
|
| 546 |
#[test] |
| 547 |
fn test_try_wait() { |
| 548 |
let child = SharedChild::spawn(&mut sleep_forever_cmd()).unwrap(); |
| 549 |
let maybe_status = child.try_wait().unwrap(); |
| 550 |
assert_eq!(maybe_status, None); |
| 551 |
child.kill().unwrap(); |
| 552 |
// The child will handle that signal asynchronously, so we check it |
| 553 |
// repeatedly in a busy loop. |
| 554 |
let mut maybe_status = None; |
| 555 |
while maybe_status.is_none() { |
| 556 |
maybe_status = child.try_wait().unwrap(); |
| 557 |
} |
| 558 |
assert!(maybe_status.is_some()); |
| 559 |
assert!(!maybe_status.unwrap().success()); |
| 560 |
} |
| 561 |
|
| 562 |
#[test] |
| 563 |
fn test_many_waiters() { |
| 564 |
let child = Arc::new(SharedChild::spawn(&mut sleep_forever_cmd()).unwrap()); |
| 565 |
let mut threads = Vec::new(); |
| 566 |
for _ in 0..10 { |
| 567 |
let clone = child.clone(); |
| 568 |
threads.push(std::thread::spawn(move || clone.wait())); |
| 569 |
} |
| 570 |
child.kill().unwrap(); |
| 571 |
for thread in threads { |
| 572 |
thread.join().unwrap().unwrap(); |
| 573 |
} |
| 574 |
} |
| 575 |
|
| 576 |
#[test] |
| 577 |
fn test_waitid_after_exit_doesnt_hang() { |
| 578 |
// There are ominous reports (https://bugs.python.org/issue10812) of a |
| 579 |
// broken waitid implementation on OSX, which might hang forever if it |
| 580 |
// tries to wait on a child that's already exited. |
| 581 |
let mut child = true_cmd().spawn().unwrap(); |
| 582 |
sys::wait_noreap(sys::get_handle(&child)).unwrap(); |
| 583 |
// At this point the child has definitely exited. Wait again to test |
| 584 |
// that a second wait doesn't block. |
| 585 |
sys::wait_noreap(sys::get_handle(&child)).unwrap(); |
| 586 |
// Clean up the child to avoid leaving a zombie. |
| 587 |
child.wait().unwrap(); |
| 588 |
} |
| 589 |
|
| 590 |
#[test] |
| 591 |
fn test_into_inner_before_wait() { |
| 592 |
let shared_child = SharedChild::spawn(&mut sleep_forever_cmd()).unwrap(); |
| 593 |
let mut child = shared_child.into_inner(); |
| 594 |
child.kill().unwrap(); |
| 595 |
child.wait().unwrap(); |
| 596 |
} |
| 597 |
|
| 598 |
#[test] |
| 599 |
fn test_into_inner_after_wait() { |
| 600 |
// This makes sure the child's inner state is valid. If we used waitpid |
| 601 |
// on the side, the inner child would try to wait again and cause an |
| 602 |
// error. |
| 603 |
let shared_child = SharedChild::spawn(&mut sleep_forever_cmd()).unwrap(); |
| 604 |
shared_child.kill().unwrap(); |
| 605 |
shared_child.wait().unwrap(); |
| 606 |
let mut child = shared_child.into_inner(); |
| 607 |
// Wait should succeed. (Note that we also used to test that |
| 608 |
// child.kill() failed here, but its behavior changed in Rust 1.72.) |
| 609 |
child.wait().unwrap(); |
| 610 |
} |
| 611 |
|
| 612 |
#[test] |
| 613 |
fn test_new() -> Result<(), Box<dyn Error>> { |
| 614 |
// Spawn a short-lived child. |
| 615 |
let mut command = cat_cmd(); |
| 616 |
command.stdin(Stdio::piped()); |
| 617 |
command.stdout(Stdio::null()); |
| 618 |
let mut child = command.spawn()?; |
| 619 |
let child_stdin = child.stdin.take().unwrap(); |
| 620 |
|
| 621 |
// Construct a SharedChild from the Child, which has not yet been waited on. The child is |
| 622 |
// blocked on stdin, so we know it hasn't yet exited. |
| 623 |
let mut shared_child = SharedChild::new(child).unwrap(); |
| 624 |
assert!(matches!( |
| 625 |
shared_child.inner.lock().unwrap().state, |
| 626 |
NotWaiting, |
| 627 |
)); |
| 628 |
|
| 629 |
// Now close the child's stdin. This will cause the child to exit. |
| 630 |
drop(child_stdin); |
| 631 |
|
| 632 |
// Construct more SharedChild objects from the same child, in a loop. Eventually one of |
| 633 |
// them will notice that the child has exited. |
| 634 |
loop { |
| 635 |
shared_child = SharedChild::new(shared_child.into_inner())?; |
| 636 |
if let Exited(status) = shared_child.inner.lock().unwrap().state { |
| 637 |
assert!(status.success()); |
| 638 |
return Ok(()); |
| 639 |
} |
| 640 |
} |
| 641 |
} |
| 642 |
|
| 643 |
#[test] |
| 644 |
fn test_takes() -> Result<(), Box<dyn Error>> { |
| 645 |
let mut command = true_cmd(); |
| 646 |
command.stdin(Stdio::piped()); |
| 647 |
command.stdout(Stdio::piped()); |
| 648 |
command.stderr(Stdio::piped()); |
| 649 |
let shared_child = SharedChild::spawn(&mut command)?; |
| 650 |
|
| 651 |
assert!(shared_child.take_stdin().is_some()); |
| 652 |
assert!(shared_child.take_stdout().is_some()); |
| 653 |
assert!(shared_child.take_stderr().is_some()); |
| 654 |
|
| 655 |
assert!(shared_child.take_stdin().is_none()); |
| 656 |
assert!(shared_child.take_stdout().is_none()); |
| 657 |
assert!(shared_child.take_stderr().is_none()); |
| 658 |
|
| 659 |
shared_child.wait()?; |
| 660 |
Ok(()) |
| 661 |
} |
| 662 |
|
| 663 |
#[test] |
| 664 |
fn test_wait_try_wait_race() -> Result<(), Box<dyn Error>> { |
| 665 |
// Make sure that .wait() and .try_wait() can't race against each other. The scenario we're |
| 666 |
// worried about is: |
| 667 |
// 1. wait() takes the lock, set the state to Waiting, and releases the lock. |
| 668 |
// 2. try_wait swoops in, takes the lock, sees the Waiting state, and returns Ok(None). |
| 669 |
// 3. wait() resumes, actually calls waitit(), observes the child has exited, retakes the |
| 670 |
// lock, reaps the child, and sets the state to Exited. |
| 671 |
// A race like this could cause .try_wait() to report that the child hasn't exited, even if |
| 672 |
// in fact the child exited long ago. A subsequent call to .try_wait() would almost |
| 673 |
// certainly report Ok(Some(_)), but the first call is still a bug. The way to prevent the |
| 674 |
// bug is by making .wait() do a non-blocking call to waitid() before releasing the lock. |
| 675 |
// |
| 676 |
// This was a failing test when I first committed it. Most of the time it would fail after |
| 677 |
// a few hundred iterations, but sometimes it took thousands. Default to one second so that |
| 678 |
// the tests don't take too long, but use an env var to configure a really big run in CI. |
| 679 |
let mut test_duration_secs: u64 = 1; |
| 680 |
if let Ok(test_duration_secs_str) = std::env::var("SHARED_CHILD_RACE_TEST_SECONDS") { |
| 681 |
dbg!(&test_duration_secs_str); |
| 682 |
test_duration_secs = test_duration_secs_str.parse().expect("invalid u64"); |
| 683 |
} |
| 684 |
let test_duration = Duration::from_secs(test_duration_secs); |
| 685 |
let test_start = Instant::now(); |
| 686 |
let mut iterations = 1u64; |
| 687 |
loop { |
| 688 |
// Start a child that will exit immediately. |
| 689 |
let child = SharedChild::spawn(&mut true_cmd())?; |
| 690 |
// Wait for the child to exit, without updating the SharedChild state. |
| 691 |
let handle = sys::get_handle(&child.inner.lock().unwrap().child); |
| 692 |
sys::wait_noreap(handle)?; |
| 693 |
// Spawn two threads, one to wait() and one to try_wait(). It should be impossible for the |
| 694 |
// try_wait thread to return Ok(None) at this point. However, we want to make sure there's |
| 695 |
// no race condition between them, where the wait() thread has said it's waiting and |
| 696 |
// released the child lock but hasn't yet actually waited. |
| 697 |
let barrier = std::sync::Barrier::new(2); |
| 698 |
let try_wait_ret = std::thread::scope(|scope| { |
| 699 |
scope.spawn(|| { |
| 700 |
barrier.wait(); |
| 701 |
child.wait().unwrap(); |
| 702 |
}); |
| 703 |
scope |
| 704 |
.spawn(|| { |
| 705 |
barrier.wait(); |
| 706 |
child.try_wait().unwrap() |
| 707 |
}) |
| 708 |
.join() |
| 709 |
.unwrap() |
| 710 |
}); |
| 711 |
let test_time_so_far = Instant::now().saturating_duration_since(test_start); |
| 712 |
assert!( |
| 713 |
try_wait_ret.is_some(), |
| 714 |
"encountered the race condition after {test_time_so_far:?} ({iterations} iterations)", |
| 715 |
); |
| 716 |
iterations += 1; |
| 717 |
|
| 718 |
// If we've met the target test duration (1 sec by default), exit with success. |
| 719 |
// Otherwise keep looping and trying to provoke the race. |
| 720 |
if test_time_so_far >= test_duration { |
| 721 |
return Ok(()); |
| 722 |
} |
| 723 |
} |
| 724 |
} |
| 725 |
} |