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.

pstree.rs 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. use procinfo::pid;
  2. /// Datenstruktur für einen Prozess.
  3. pub struct Process {
  4. name: String,
  5. pid: i32,
  6. ppid: i32,
  7. }
  8. impl Process {
  9. /// Erstellt eine Prozess-Datenstruktur aus procinfo::Stat.
  10. pub fn new(with_pid: i32) -> Self {
  11. if let Ok(stat) = pid::stat(with_pid) {
  12. Process {
  13. name: stat.command,
  14. pid: stat.pid,
  15. ppid: stat.ppid,
  16. }
  17. } else {
  18. panic!("Internal Error: Process not found")
  19. }
  20. }
  21. /// Erstellt eine Prozess-Datenstruktur aus procinfo::Stat.
  22. pub fn me() -> Self {
  23. if let Ok(my_pid) = pid::stat_self() {
  24. Process::new(my_pid.pid)
  25. } else {
  26. panic!("Internal Error: I don't have a PID but I am running.")
  27. }
  28. }
  29. /// Prüft ob das Prozess-Struct ein Elternprozess besitzt.
  30. pub fn has_parent(&self) -> bool {
  31. self.ppid != 0
  32. }
  33. /// Gibt den Elternprozess zurück.
  34. pub fn parent(&self) -> Self {
  35. Process::new(self.ppid)
  36. }
  37. /// Prüft ob das Prozess-Struct einen (entfernten) Elternprozess mit dem übergebenen pid hat.
  38. pub fn has_parent_with_pid(&self, pid: i32) -> bool {
  39. if self.pid == pid {
  40. return true;
  41. }
  42. if self.has_parent() {
  43. return self.parent().has_parent_with_pid(pid);
  44. }
  45. false
  46. }
  47. /// Gibt über Rekursion über die Eltern eine Prozesskette aus.
  48. pub fn print_recursive(&self, to_pid: i32, output: &mut String) {
  49. if output.len() == 0 {
  50. *output = format!("{}({}){}", self.name, self.pid, output);
  51. } else {
  52. *output = format!("{}({})---{}", self.name, self.pid, output);
  53. }
  54. if self.has_parent() && self.pid != to_pid {
  55. self.parent().print_recursive(to_pid, output);
  56. }
  57. }
  58. }
  59. /// Geht von eigenem Prozess aus und gibt die Prozesskette bis zum übergebenem PID aus
  60. /// und fängt mögliche Fehler ab.
  61. pub fn print(pid: i32) -> bool {
  62. if let Err(_) = pid::stat(pid) {
  63. println!("Invalid PID");
  64. return false;
  65. }
  66. let my_proc = Process::me();
  67. if !my_proc.has_parent_with_pid(pid) {
  68. println!("This Process has no parent {}", pid);
  69. return false;
  70. }
  71. let mut output = String::new();
  72. my_proc.print_recursive(pid, &mut output);
  73. println!("{}", output);
  74. true
  75. }