No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mod.rs 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. use nix::unistd::{fork, getpid};
  2. use nix::sys::wait::wait;
  3. use nix::sys::wait::WaitStatus;
  4. use nix::unistd::ForkResult::{Child, Parent};
  5. mod pstree;
  6. /// Required function.
  7. /// Accepts parameter *start_pid* which will be root-process in the printed pstree.
  8. /// Parses parameter *arg* as the number of forked processes.
  9. pub fn run_childs(start_pid: i32, arg: &str) -> Result<(), String> {
  10. let count = arg.parse::<u8>();
  11. match count {
  12. Ok(value) => {
  13. if value > 0 {
  14. fork_children(0, value - 1, start_pid);
  15. }
  16. Ok(())
  17. }
  18. Err(_) => {
  19. Err(
  20. "Failed to parse arguments. PIDs must be decimal.\n".to_string(),
  21. )
  22. }
  23. }
  24. }
  25. /// Private function, which forks specified amount of processes (*count*) through recursion
  26. fn fork_children(count: u8, to: u8, start_pid: i32) {
  27. let pid = fork();
  28. match pid {
  29. Ok(Child) => {
  30. println!("hello, I am child (pid:{})", getpid());
  31. if count < to {
  32. fork_children(count + 1, to, start_pid);
  33. } else {
  34. println!();
  35. pstree::print(start_pid);
  36. }
  37. }
  38. Ok(Parent { child }) => {
  39. if let Ok(ws) = wait() {
  40. if let WaitStatus::Exited(child_pid, exit_code) = ws {
  41. println!(
  42. "I am {} and my child is {}. After I waited for {}, it sent me status {:?}",
  43. getpid(),
  44. child,
  45. child_pid,
  46. exit_code
  47. );
  48. }
  49. }
  50. }
  51. Err(_) => {}
  52. }
  53. }