[go: up one dir, main page]

Crate sigchld

Source
Expand description

§sigchld Actions Status crates.io docs.rs

This is a low-level utility for child process management. Unix doesn’t provide a portable* API for waiting for a child process to exit with a timeout. The closest thing is waiting for the SIGCHLD signal to be delivered, but Unix signal handling is quite complicated and error-prone. This crate implements SIGCHLD handling (using signal_hook internally for compatibility with other signal handling libraries) and allows any number of threads to wait for that signal, with an optional timeout.

Note that SIGCHLD indicates that any child process has exited, but there’s no (100% reliable) way to know which child it was. You need to poll your child process in a loop, and wait again if it hasn’t exited yet. Most applications will want a higher-level crate that does this loop internally; I’ll list such crates here as they’re implemented.

* Linux supports signalfd, but there’s no equivalent on e.g. macOS.

§Example

// Create a waiter before spawning the child, to guarantee that we don't miss a signal.
let waiter = sigchld::Waiter::new()?;

// Start a child process that sleeps for up to 3 seconds.
let sleep_time: f32 = rand::random_range(0.0..=3.0);
println!("Sleeping for {sleep_time:.3} seconds...", );
std::process::Command::new("sleep").arg(format!("{sleep_time}")).spawn()?;

// Wait half a second for *any* child to exit. In this example `sleep` is the only child
// process, but in general we won't necessarily know which child woke us up.
let signaled: bool = waiter.wait_timeout(Duration::from_secs(1))?;

if signaled {
    // In *this example* we know that the signal came from `sleep`.
    println!("Sleep exited.");
} else {
    println!("We gave up waiting after 1 sec.");
}

Structs§

Waiter
An object that buffers SIGCHLD signals so that you can wait on them reliably.