Skip to content

Commit 8028591

Browse files
committed
add sample program for 11_8
1 parent e5d66a5 commit 8028591

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

chapter11/Cargo.toml

+4
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,7 @@ path = "src/11_2_3/main.rs"
4242
[[bin]]
4343
name = "11_3"
4444
path = "src/11_3/main.rs"
45+
46+
[[bin]]
47+
name = "11_8"
48+
path = "src/11_8/main.rs"

chapter11/src/11_8/main.rs

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
use nix::sys::wait::*;
2+
use nix::unistd::{execve, fork, ForkResult};
3+
use std::env;
4+
use std::ffi::CString;
5+
6+
// Go のプログラミングでは触れることのない世界として言及されているが、Rust では触れることができる。
7+
// 本書の中で fork(2) と execve(3) が言及されていたので、それを使用したサンプルプログラムを掲載しておく。
8+
fn main() {
9+
// fork
10+
match unsafe { fork() }.expect("fork failed") {
11+
ForkResult::Parent { child } => {
12+
// waitpid
13+
match waitpid(child, None).expect("wait_pid failed") {
14+
WaitStatus::Exited(pid, status) => {
15+
println!("exit!: pid={:?}, status={:?}", pid, status)
16+
}
17+
WaitStatus::Signaled(pid, status, _) => {
18+
println!("signal!: pid={:?}, status={:?}", pid, status)
19+
}
20+
_ => println!("abnormal exit!"),
21+
}
22+
}
23+
ForkResult::Child => {
24+
// 引数の値を取得する。
25+
let args: Vec<String> = env::args().collect();
26+
let dir = CString::new(args[1].to_string()).unwrap();
27+
let arg = CString::new(args[2].to_string()).unwrap();
28+
// env は仮で入れておく。
29+
let env = CString::new("ENV=prd".to_string()).unwrap();
30+
31+
// execv
32+
execve(&dir, &[dir.clone(), arg], &[env]).expect("execution failed.");
33+
}
34+
}
35+
}

0 commit comments

Comments
 (0)