Brak opisu
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.3KB

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