Debian Codegraph @

debian/rust-vendor/procfs/examples/process_hierarchy.rs

raw
1 use procfs::process::{all_processes, Stat};
2
3 struct ProcessEntry {
4 stat: Stat,
5 cmdline: Option<Vec<String>>,
6 }
7
8 /// Print all processes as a tree.
9 /// The tree reflects the hierarchical relationship between parent and child processes.
10 fn main() {
11 // Get all processes
12 let processes: Vec<ProcessEntry> = match all_processes() {
13 Err(err) => {
14 println!("Failed to read all processes: {}", err);
15 return;
16 }
17 Ok(processes) => processes,
18 }
19 .filter_map(|v| {
20 v.and_then(|p| {
21 let stat = p.stat()?;
22 let cmdline = p.cmdline().ok();
23 Ok(ProcessEntry { stat, cmdline })
24 })
25 .ok()
26 })
27 .collect();
28 // Iterate through all processes and start with top-level processes.
29 // Those can be identified by checking if their parent PID is zero.
30 for process in &processes {
31 if process.stat.ppid == 0 {
32 print_process(process, &processes, 0);
33 }
34 }
35 }
36
37 /// Take a process, print its command and recursively list all child processes.
38 /// This function will call itself until no further children can be found.
39 /// It's a depth-first tree exploration.
40 ///
41 /// depth: The hierarchical depth of the process
42 fn print_process(process: &ProcessEntry, all_processes: &Vec<ProcessEntry>, depth: usize) {
43 let cmdline = match &process.cmdline {
44 Some(cmdline) => cmdline.join(" "),
45 None => "zombie process".into(),
46 };
47
48 // Some processes seem to have an empty cmdline.
49 if cmdline.is_empty() {
50 return;
51 }
52
53 // 10 characters width for the pid
54 let pid_length = 8;
55 let mut pid = process.stat.pid.to_string();
56 pid.push_str(&" ".repeat(pid_length - pid.len()));
57
58 let padding = " ".repeat(4 * depth);
59 println!("{}{}{}", pid, padding, cmdline);
60
61 let children = get_children(process.stat.pid, all_processes);
62 for child in &children {
63 print_process(child, all_processes, depth + 1);
64 }
65 }
66
67 /// Get all children of a specific process, by iterating through all processes and
68 /// checking their parent pid.
69 fn get_children(pid: i32, all_processes: &[ProcessEntry]) -> Vec<&ProcessEntry> {
70 all_processes
71 .iter()
72 .filter(|process| process.stat.ppid == pid)
73 .collect()
74 }