#![cfg(unix)]
use std::collections::HashSet;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Proc {
pub(crate) pid: i32,
pub(crate) ppid: i32,
pub(crate) pgid: i32,
}
pub(crate) fn descendant_groups(table: &[Proc], root: i32, exclude: i32) -> Vec<i32> {
let mut groups = vec![];
let mut seen = HashSet::from([root]);
let mut frontier = vec![root];
while let Some(parent) = frontier.pop() {
for p in table.iter().filter(|p| p.ppid == parent) {
if !seen.insert(p.pid) {
continue;
}
frontier.push(p.pid);
if p.pgid > 1 && p.pgid != root && p.pgid != exclude && !groups.contains(&p.pgid) {
groups.push(p.pgid);
}
}
}
groups
}
pub(crate) fn parse_ps(out: &str) -> Vec<Proc> {
out.lines()
.filter_map(|line| {
let mut n = line.split_whitespace().map(str::parse::<i32>);
match (n.next(), n.next(), n.next()) {
(Some(Ok(pid)), Some(Ok(ppid)), Some(Ok(pgid))) => Some(Proc { pid, ppid, pgid }),
_ => None,
}
})
.collect()
}
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
pub(crate) fn parse_proc_stat(stat: &str) -> Option<Proc> {
let pid = stat.split_whitespace().next()?.parse().ok()?;
let mut rest = stat.get(stat.rfind(')')? + 1..)?.split_whitespace();
let _state = rest.next()?;
let ppid = rest.next()?.parse().ok()?;
let pgid = rest.next()?.parse().ok()?;
Some(Proc { pid, ppid, pgid })
}
pub(crate) fn snapshot() -> Vec<Proc> {
#[cfg(target_os = "linux")]
if let Ok(entries) = std::fs::read_dir("/proc") {
return entries
.flatten()
.filter_map(|e| std::fs::read_to_string(e.path().join("stat")).ok())
.filter_map(|stat| parse_proc_stat(&stat))
.collect();
}
let ps = std::process::Command::new("ps")
.args(["-A", "-o", "pid=,ppid=,pgid="])
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output();
match ps {
Ok(out) if out.status.success() => parse_ps(&String::from_utf8_lossy(&out.stdout)),
other => {
tracing::debug!(?other, "could not read the process table");
vec![]
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_proc_stat_with_odd_comm() {
let row = parse_proc_stat("123 (a) b (c)) S 45 67 67 0 -1");
assert_eq!(row, Some(Proc { pid: 123, ppid: 45, pgid: 67 }));
}
}