1 extern crate nix;
2 use nix::sched::{self, CloneFlags};
3 use nix::sys::wait::{waitpid, WaitStatus};
4 use nix::unistd::{self, fork, ForkResult};
5 use std::process;
6
main()7 fn main() {
8 let clone_flags = CloneFlags::CLONE_NEWPID | CloneFlags::CLONE_NEWNS;
9
10 println!("Parent process. PID: {}", unistd::getpid());
11 unsafe {
12 match fork() {
13 Ok(ForkResult::Parent { child }) => {
14 println!("Parent process. Child PID: {}", child);
15 match waitpid(child, None) {
16 Ok(WaitStatus::Exited(pid, status)) => {
17 println!("Child {} exited with status: {}", pid, status);
18 }
19 Ok(_) => println!("Child process did not exit normally."),
20 Err(e) => println!("Error waiting for child process: {:?}", e),
21 }
22 }
23 Ok(ForkResult::Child) => {
24 // 使用 unshare 创建新的命名空间
25 println!("Child process. PID: {}", unistd::getpid());
26 if let Err(e) = sched::unshare(clone_flags) {
27 println!("Failed to unshare: {:?}", e);
28 process::exit(1);
29 }
30 println!("Child process. PID: {}", unistd::getpid());
31 }
32 Err(err) => {
33 println!("Fork failed: {:?}", err);
34 process::exit(1);
35 }
36 }
37 }
38 }
39