$ cargo run ls
$ cargo run cmd-not-exists
[package] | |
name = "rust-demo-spawn" | |
version = "0.1.0" | |
authors = ["Hugo Wang <w@mitnk.com>"] | |
[dependencies] | |
nix = "0.10.0" | |
libc = "0.2.0" |
extern crate nix; | |
extern crate libc; | |
use std::env; | |
use std::process::Command; | |
use std::os::unix::process::CommandExt; | |
use nix::sys::signal; | |
extern "C" fn handle_sigchld(_: i32) { | |
match nix::sys::wait::waitpid(None, None) { | |
Ok(x) => { | |
println!("waitpid ok: {:?}", x); | |
} | |
Err(e) => { | |
println!("waitpid error: {:?}", e); | |
} | |
} | |
} | |
fn main() { | |
let sig_action = signal::SigAction::new( | |
signal::SigHandler::Handler(handle_sigchld), | |
signal::SaFlags::empty(), | |
signal::SigSet::empty(), | |
); | |
unsafe { | |
match signal::sigaction(signal::SIGCHLD, &sig_action) { | |
Ok(_) => {} | |
Err(e) => println!("sigaction error: {:?}", e), | |
} | |
} | |
let args: Vec<String> = env::args().collect(); | |
println!("{:?}", args); | |
let mut p = Command::new(&args[1]); | |
p.before_exec(move || { | |
unsafe { | |
let pid = libc::getpid(); | |
let code = libc::setpgid(0, pid); | |
println!("code: {}", code); | |
} | |
Ok(()) | |
}); | |
match p.spawn() { | |
Ok(mut child) => { | |
println!("spawn ok: {:?}", child); | |
match child.wait() { | |
Ok(x) => println!("ok: {:?}", x), | |
Err(e) => println!("err: {:?}", e), | |
} | |
} | |
Err(e) => { | |
println!("spawn error: {:?}", e); | |
} | |
} | |
println!("the end."); | |
} |