|
|
@@ -1,5 +1,6 @@
|
|
1
|
1
|
use nix::unistd::{fork, getpid};
|
|
2
|
2
|
use nix::sys::wait::wait;
|
|
|
3
|
+use nix::sys::wait::WaitStatus;
|
|
3
|
4
|
use nix::unistd::ForkResult::{Child, Parent};
|
|
4
|
5
|
|
|
5
|
6
|
mod pstree;
|
|
|
@@ -8,29 +9,38 @@ pub fn run_childs(start_pid: i32, arg: &str) -> Result<(), String> {
|
|
8
|
9
|
let count = arg.parse::<u8>();
|
|
9
|
10
|
match count {
|
|
10
|
11
|
Ok(value) => {
|
|
11
|
|
- for i in 0..value {
|
|
12
|
|
- let pid = fork();
|
|
13
|
|
- match pid {
|
|
14
|
|
- Ok(Child) => {
|
|
15
|
|
- println!("hello, I am child (pid:{})", getpid());
|
|
16
|
|
- }
|
|
17
|
|
- Ok(Parent { child }) => {
|
|
18
|
|
- println!("hello, I am parent of {} (pid:{})", child, getpid());
|
|
19
|
|
- match wait(){
|
|
20
|
|
- Ok(ws) => { println!("{:?}", ws); }
|
|
21
|
|
- Err(_) => {}
|
|
22
|
|
- }
|
|
23
|
|
- }
|
|
24
|
|
- // panic, fork should never fail unless there is a
|
|
25
|
|
- // serious problem with the OS
|
|
26
|
|
- Err(_) => panic!("fork failed"),
|
|
27
|
|
- }
|
|
28
|
|
- }
|
|
29
|
|
- pstree::print(start_pid);
|
|
|
12
|
+
|
|
|
13
|
+ if value > 0 { }
|
|
|
14
|
+ fork_children(0, value - 1, start_pid);
|
|
30
|
15
|
Ok(())
|
|
31
|
16
|
},
|
|
32
|
17
|
Err(_) => {
|
|
33
|
18
|
Err("Parse Failed".to_string())
|
|
34
|
19
|
},
|
|
35
|
20
|
}
|
|
|
21
|
+}
|
|
|
22
|
+
|
|
|
23
|
+pub fn fork_children(count: u8, to:u8, start_pid: i32) {
|
|
|
24
|
+ let pid = fork();
|
|
|
25
|
+ match pid {
|
|
|
26
|
+ Ok(Child) => {
|
|
|
27
|
+ println!("hello, I am child (pid:{})", getpid());
|
|
|
28
|
+ if count < to {
|
|
|
29
|
+ fork_children(count + 1, to, start_pid);
|
|
|
30
|
+ } else {
|
|
|
31
|
+ println!();
|
|
|
32
|
+ pstree::print(start_pid);
|
|
|
33
|
+ }
|
|
|
34
|
+ }
|
|
|
35
|
+
|
|
|
36
|
+ Ok(Parent { child }) => {
|
|
|
37
|
+ if let Ok(ws) = wait() {
|
|
|
38
|
+ if let WaitStatus::Exited(child_pid, exit_code) = ws {
|
|
|
39
|
+ println!("I am {} and my child is {}. After I waited for {}, it sent me status {:?}", getpid(), child, child_pid, exit_code);
|
|
|
40
|
+ }
|
|
|
41
|
+ }
|
|
|
42
|
+ }
|
|
|
43
|
+
|
|
|
44
|
+ Err(_) => {}
|
|
|
45
|
+ }
|
|
36
|
46
|
}
|