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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.