use std::collections::HashMap;
use sysinfo::{ProcessRefreshKind, ProcessesToUpdate, System};
pub fn child_tree(pid: u32, with_root: bool) -> Vec<u32> {
let mut sys = System::new();
sys.refresh_processes_specifics(ProcessesToUpdate::All, true, ProcessRefreshKind::new());
let mut children: HashMap<u32, Vec<(u64, u32)>> = HashMap::new();
for (child, process) in sys.processes() {
if is_console_host(process) {
continue;
}
if let Some(parent) = process.parent() {
let (parent, child) = (parent.as_u32(), child.as_u32());
if parent != child {
children
.entry(parent)
.or_default()
.push((process.start_time(), child));
}
}
}
for list in children.values_mut() {
list.sort_unstable();
}
let mut out = Vec::new();
collect(pid, &children, &mut out, 0);
if with_root {
out.push(pid);
}
out
}
#[cfg(windows)]
fn is_console_host(process: &sysinfo::Process) -> bool {
let name = process.name().to_string_lossy().to_ascii_lowercase();
name == "conhost.exe" || name == "openconsole.exe"
}
#[cfg(not(windows))]
fn is_console_host(_process: &sysinfo::Process) -> bool {
false
}
fn collect(pid: u32, children: &HashMap<u32, Vec<(u64, u32)>>, out: &mut Vec<u32>, depth: usize) {
if depth > 256 {
return;
}
if let Some(list) = children.get(&pid) {
for &(_, child) in list {
if out.contains(&child) || child == pid {
continue;
}
collect(child, children, out, depth + 1);
out.push(child);
}
}
}