Spawn And Poll With try_wait

Start a child process with spawn and probe it non-blockingly via try_wait: None means still running, and wait() finally blocks for the exit status.

RustCli Tooling

Code

rustsnippet
24 lines
use std::process::Command;
use std::thread;
use std::time::Duration;

fn main() {
    // spawn 立即返回句柄:子进程在后台运行
    let mut child = Command::new("git").arg("--version").spawn().expect("git available");

    // try_wait 非阻塞探测:None 表示还在跑,Some 携带退出状态
    for _ in 0..10 {
        match child.try_wait().expect("wait failed") {
            Some(status) => {
                println!("exited: {status}");
                break;
            }
            None => println!("still running"),
        }
        thread::sleep(Duration::from_millis(10));
    }

    // 兜底阻塞等待,拿到最终退出状态
    let status = child.wait().expect("wait failed");
    println!("success: {}", status.success());
}

A plain account of the logic

Spawn And Poll With try_wait reduces to the function main.

A single loop drives the file — for _ in 0..10. The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.

Watch out for

  • No dependency resolution ever runs; the toolchain by itself suffices.

Using it

The signature that sets the pace: fn main()

Expect labeled output — exited:, still running, success: — when the file runs.

Key statements

Some(status) => {
    println!("exited: {status}");
    break;
}

Interactive Tools for This Topic

FAQ

What does Spawn And Poll With try_wait print when run?
Running the file directly is enough — expect labeled output lines such as `exited:`, `still running`, `success:`.