Program forks and parent waits for child

This commit is contained in:
Elnath 2025-04-18 18:23:10 +02:00
parent 46d173bd56
commit 0528a6af22
1 changed files with 35 additions and 5 deletions

View File

@ -1,9 +1,39 @@
use nix::unistd::execv; use nix::unistd::{execv, fork, ForkResult};
use std::ffi::CString; use std::ffi::CString;
use std::process::ExitCode;
use nix::sys::wait::{waitid, WaitPidFlag, WaitStatus};
fn main() { fn main() -> ExitCode {
println!("I am executing {}!", env!("TEST_PROG_PATH")); let child_exec_path = CString::new(env!("TEST_PROG_PATH")).unwrap();
let path = CString::new(env!("TEST_PROG_PATH")).unwrap(); match unsafe{fork()} {
execv(&path, &[&path]).unwrap(); Ok(ForkResult::Child) => {
// ⚠️ There is a limited amount of things that can be done here, see fork's safety
execv(&child_exec_path, &[&child_exec_path]).unwrap();
unreachable!();
}
Ok(ForkResult::Parent { child: child_pid }) => {
println!("✔️ Started child {child_pid}");
println!("⏳️ Waiting for child to exit...");
use nix::sys::wait::Id::Pid;
match waitid(Pid(child_pid), WaitPidFlag::WEXITED) {
Err(e) => {
println!("❌ Wait failed: {e}");
ExitCode::FAILURE
}
Ok(WaitStatus::Exited(_pid, exit_code)) => {
println!("👋 child exited with code {exit_code}");
ExitCode::SUCCESS
}
Ok(status) => {
println!("⚠️ Unexpected status from wait! {status:#?}");
ExitCode::FAILURE
}
}
}
Err(e) => {
println!("❌ Fork failed: {e}");
ExitCode::FAILURE
}
}
} }