waitpid_nohang

Function waitpid_nohang 

Source
pub fn waitpid_nohang(pid: pid_t) -> Result<Option<c_int>>
Expand description

Wait for process to change status without blocking see wait(2)

This is the non-blocking variant of waitpid(). It checks if the child has changed status and returns immediately without blocking.

§Return Value

  • Ok(Some(status)) - Child has exited/stopped with the given status
  • Ok(None) - Child is still running (no state change)
  • Err(...) - Error occurred (e.g., ECHILD if child doesn’t exist)

§Behavior

  • Returns immediately (does not block)
  • Retries automatically on EINTR (interrupted by signal)
  • Returns the raw status (use libc::WIFEXITED, libc::WEXITSTATUS, etc.)

§Use Cases

  • Process supervisors - Monitor multiple children without blocking
  • Event loops - Check child status while handling other events
  • Polling patterns - Parent has other work to do while child runs
  • Non-blocking checks - Determine if child is still running

§Example

use fork::{fork, Fork, waitpid_nohang};
use std::time::Duration;

match fork::fork() {
    Ok(Fork::Parent(child)) => {
        // Do work while child runs
        for i in 0..5 {
            println!("Parent working... iteration {}", i);
            std::thread::sleep(Duration::from_millis(100));

            match waitpid_nohang(child) {
                Ok(Some(status)) => {
                    println!("Child exited with status: {}", status);
                    break;
                }
                Ok(None) => {
                    println!("Child still running...");
                }
                Err(e) => {
                    eprintln!("Error checking child: {}", e);
                    break;
                }
            }
        }
    }
    Ok(Fork::Child) => {
        // Child does work
        std::thread::sleep(Duration::from_millis(250));
        std::process::exit(0);
    }
    Err(e) => eprintln!("Fork failed: {}", e),
}

§Errors

Returns an io::Error if the waitpid system call fails. Common errors include:

  • No child process exists with the given PID (ECHILD)
  • Invalid options or PID