#child-process #child #process #subprocess #command


a library for using child processes from multiple threads

10 releases (1 stable)

1.0.0 Nov 16, 2021
0.3.5 Mar 15, 2021
0.3.4 Sep 7, 2019
0.3.3 Jul 26, 2018
0.1.0 Feb 6, 2017

#87 in Operating systems

Download history 87797/week @ 2023-12-13 63844/week @ 2023-12-20 54119/week @ 2023-12-27 83397/week @ 2024-01-03 77137/week @ 2024-01-10 89622/week @ 2024-01-17 86854/week @ 2024-01-24 128824/week @ 2024-01-31 143366/week @ 2024-02-07 136387/week @ 2024-02-14 139061/week @ 2024-02-21 135082/week @ 2024-02-28 103696/week @ 2024-03-06 100625/week @ 2024-03-13 100026/week @ 2024-03-20 69333/week @ 2024-03-27

399,024 downloads per month
Used in 266 crates (17 directly)

MIT license

369 lines

shared_child.rs Actions Status crates.io docs.rs

A library for awaiting and killing child processes from multiple threads.

The std::process::Child type in the standard library provides wait and kill methods that take &mut self, making it impossible to kill a child process while another thread is waiting on it. That design works around a race condition in Unix's waitpid function, where a PID might get reused as soon as the wait returns, so a signal sent around the same time could accidentally get delivered to the wrong process.

However with the newer POSIX waitid function, we can wait on a child without freeing its PID for reuse. That makes it safe to send signals concurrently. Windows has actually always supported this, by preventing PID reuse while there are still open handles to a child process. This library wraps std::process::Child for concurrent use, backed by these APIs.

Compatibility note: The libc crate doesn't currently support waitid on NetBSD or OpenBSD, or on older versions of OSX. There might also be some version of OSX where the waitid function exists but is broken. We can add a "best effort" workaround using waitpid for these platforms as we run into them. Please file an issue if you hit this.


use shared_child::SharedChild;
use std::process::Command;
use std::sync::Arc;

// Spawn a child that will just sleep for a long time,
// and put it in an Arc to share between threads.
let mut command = Command::new("python");
command.arg("-c").arg("import time; time.sleep(1000000000)");
let shared_child = SharedChild::spawn(&mut command).unwrap();
let child_arc = Arc::new(shared_child);

// On another thread, wait on the child process.
let child_arc_clone = child_arc.clone();
let thread = std::thread::spawn(move || {

// While the other thread is waiting, kill the child process.
// This wouldn't be possible with e.g. Arc<Mutex<Child>> from
// the standard library, because the waiting thread would be
// holding the mutex.

// Join the waiting thread and get the exit status.
let exit_status = thread.join().unwrap();