main.rs 1.4 KB

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