Debian Codegraph @

src/collection/processes/macos.rs

raw symbols SCIP
1 //! Process data collection for macOS. Uses sysinfo and custom bindings.
2
3 pub mod sysctl_bindings;
4
5 use std::{io, process::Command};
6
7 use itertools::Itertools;
8
9 use super::UnixProcessExt;
10 use crate::{collection::Pid, utils::int_hash::IntHashMap};
11
12 pub(crate) struct MacOSProcessExt;
13
14 impl UnixProcessExt for MacOSProcessExt {
15 #[inline]
16 fn has_backup_proc_cpu_fn() -> bool {
17 true
18 }
19
20 fn backup_proc_cpu(pids: &[Pid]) -> io::Result<IntHashMap<Pid, f32>> {
21 let output = Command::new("ps")
22 .args(["-o", "pid=,pcpu=", "-p"])
23 .arg(
24 // Has to look like this since otherwise, it you hit a `unstable_name_collisions`
25 // warning.
26 Itertools::intersperse(pids.iter().map(i32::to_string), ",".to_string())
27 .collect::<String>(),
28 )
29 .output()?;
30 let mut result = IntHashMap::default();
31 String::from_utf8_lossy(&output.stdout)
32 .split_whitespace()
33 .chunks(2)
34 .into_iter()
35 .for_each(|chunk| {
36 let chunk: Vec<&str> = chunk.collect();
37 if chunk.len() != 2 {
38 panic!("Unexpected 'ps' output");
39 }
40 let pid = chunk[0].parse();
41 let usage = chunk[1].parse();
42 if let (Ok(pid), Ok(usage)) = (pid, usage) {
43 result.insert(pid, usage);
44 }
45 });
46 Ok(result)
47 }
48
49 fn parent_pid(process_val: &sysinfo::Process) -> Option<Pid> {
50 process_val
51 .parent()
52 .map(|p| p.as_u32() as _)
53 .or_else(|| fallback_macos_ppid(process_val.pid().as_u32() as _))
54 }
55 }
56
57 fn fallback_macos_ppid(pid: Pid) -> Option<Pid> {
58 sysctl_bindings::kinfo_process(pid)
59 .map(|kinfo| kinfo.kp_eproc.e_ppid)
60 .ok()
61 }