Skip to content

Instantly share code, notes, and snippets.

@mitnk

mitnk/Cargo.toml Secret

Created October 7, 2018 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mitnk/4fa6c518edc793b3a3e06540e9ca97f6 to your computer and use it in GitHub Desktop.
Save mitnk/4fa6c518edc793b3a3e06540e9ca97f6 to your computer and use it in GitHub Desktop.
wait() should either return Ok or panic

ok

$ cargo run ls

bad

$ 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.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment