File tree 2 files changed +39
-0
lines changed
2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -42,3 +42,7 @@ path = "src/11_2_3/main.rs"
42
42
[[bin ]]
43
43
name = " 11_3"
44
44
path = " src/11_3/main.rs"
45
+
46
+ [[bin ]]
47
+ name = " 11_8"
48
+ path = " src/11_8/main.rs"
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments