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