use std::time::Duration;
use fork::{ChildEvent, PreparedCommand, ProcessGroup, Signal, signal_process_group, wait_event};
fn main() -> std::io::Result<()> {
let mut command = PreparedCommand::new("/bin/sleep")?;
command.arg("30")?.process_group(ProcessGroup::New);
let child = match command.spawn(Duration::from_secs(5)) {
Ok(child) => child,
Err(error) => {
eprintln!("spawn failed: {error}");
return Ok(());
}
};
println!(
"spawned pid {} in a new process group",
child.process().get()
);
if let Some(group) = child.process_group() {
println!("signalling process group {group} with TERM");
signal_process_group(group, Signal::TERM)?;
}
match wait_event(child.process())? {
ChildEvent::Signalled { pid, signal } => {
println!("pid {} terminated by signal {signal}", pid.get());
}
ChildEvent::Exited { pid, code } => {
println!("pid {} exited with code {code}", pid.get());
}
other => println!("unexpected event: {other:?}"),
}
Ok(())
}