Lines
100 %
Functions
50 %
Branches
//! CPU time spent by a process and everything it spawned, read from `/proc`.
//!
//! A test binary running one long test prints nothing until that test ends, so
//! silence alone cannot tell a stuck run from a busy one. The hang the watchdog
//! exists for sat idle on a socket; a run burning CPU is making progress.
/// `/proc` reports CPU time in `USER_HZ` ticks, fixed at 100 by the kernel ABI.
pub const TICKS_PER_SECOND: u64 = 100;
struct Stat {
pid: u32,
ppid: u32,
pgrp: u32,
ticks: u64,
}
/// User plus system ticks of `root` and all its live descendants, each with the
/// ticks of its reaped children rolled up, so a finished process does not
/// make the total fall.
pub fn tree_ticks(root: u32) -> u64 {
let stats = read_stats();
let mut tree = vec![root];
let mut next = 0;
while let Some(&pid) = tree.get(next) {
tree.extend(stats.iter().filter(|s| s.ppid == pid).map(|s| s.pid));
next += 1;
stats
.iter()
.filter(|s| tree.contains(&s.pid))
.fold(0, |sum, s| sum.saturating_add(s.ticks))
/// Live members of the process group `pgid`, the leader included.
pub fn group_members(pgid: u32) -> Vec<u32> {
read_stats()
.filter(|s| s.pgrp == pgid)
.map(|s| s.pid)
.collect()
fn read_stats() -> Vec<Stat> {
std::fs::read_dir("/proc")
.into_iter()
.flatten()
.filter_map(|entry| std::fs::read_to_string(entry.path().join("stat")).ok())
.filter_map(|text| parse(&text))
/// A `/proc/<pid>/stat` line. The command name sits in parentheses and may
/// itself hold spaces and parentheses, so fields are counted after the last `)`.
fn parse(text: &str) -> Option<Stat> {
let (head, rest) = text.rsplit_once(')')?;
let pid = head.split_once(" (")?.0.trim().parse().ok()?;
let fields: Vec<&str> = rest.split_whitespace().collect();
let field = |index: usize| fields.get(index)?.parse::<u64>().ok();
Some(Stat {
pid,
ppid: fields.get(1)?.parse().ok()?,
pgrp: fields.get(2)?.parse().ok()?,
ticks: (11..=14).try_fold(0u64, |sum, index| sum.checked_add(field(index)?))?,
})
#[cfg(test)]
mod tests;