【发布时间】:2021-11-07 18:53:46
【问题描述】:
我有一个 Rust 进程应该启动一个子进程然后立即退出。这似乎有效:
fn main() {
// Intentionally drop the returned Child and exit
Command::new("bash").args(&["-c", "sleep 10s; touch done"]).spawn().unwrap();
}
运行此进程立即退出,bash 进程继续:
$ cargo build; target/debug/demo
$ ps aux | grep bash
dimo414 35959 0.0 0.0 4278616 1484 s001 S 1:12PM 0:00.00 bash -c sleep 10s; touch done
...
但是如果我再添加一层并尝试调用我的二进制文件并等待其完成,这似乎也在等待子进程,这与我在 shell 中观察到的不同。这是一个 MCVE:
fn main() {
let exec = std::env::current_exe().expect("Could not resolve executable location");
// First re-invoke the same binary and await it
if std::env::args().len() < 2 {
println!("Ran Subprocess:\n{:?}", Command::new(exec).arg("").output().unwrap());
} else {
// In that subprocess spawn a long-running process but don't wait
println!("Spawning Subprocess");
Command::new("bash").args(&["-c", "sleep 10s; touch done"]).spawn().unwrap();
}
}
$ cargo build; target/debug/demo
# doesn't terminate until the bash process does
有没有办法让顶层进程不等待嵌套进程完成?
【问题讨论】:
标签: unix rust subprocess