#![cfg_attr(
not(target_os = "linux"),
allow(
dead_code,
reason = "compiled on every host for pure-logic test coverage; the Linux backend is the only production caller"
)
)]
fn tail(stat: &[u8]) -> Option<&str> {
let close = stat.iter().rposition(|&b| b == b')')?;
std::str::from_utf8(stat.get(close + 1..)?).ok()
}
pub(crate) fn parse_starttime_jiffies(stat: &[u8]) -> Option<u64> {
tail(stat)?.split_whitespace().nth(19)?.parse::<u64>().ok()
}
pub(crate) fn parse_state(stat: &[u8]) -> Option<u8> {
tail(stat)?.split_whitespace().next()?.bytes().next()
}
pub(crate) fn parse_ppid(stat: &[u8]) -> Option<u32> {
tail(stat)?.split_whitespace().nth(1)?.parse::<u32>().ok()
}
pub(crate) fn parse_flags(stat: &[u8]) -> Option<u32> {
tail(stat)?.split_whitespace().nth(6)?.parse::<u32>().ok()
}
pub(crate) const PF_EXITING: u32 = 0x4;
pub(crate) fn exiting_from_stat(stat: &[u8]) -> Option<bool> {
parse_flags(stat).map(|flags| flags & PF_EXITING != 0)
}
pub(crate) fn parse_pgrp(stat: &[u8]) -> Option<u32> {
tail(stat)?.split_whitespace().nth(2)?.parse::<u32>().ok()
}
pub(crate) fn parse_num_threads(stat: &[u8]) -> Option<u64> {
tail(stat)?.split_whitespace().nth(17)?.parse::<u64>().ok()
}
pub(super) fn running_from_stat(stat: &[u8], ticks: u64) -> super::Liveness {
use super::Liveness;
match parse_starttime_jiffies(stat) {
Some(j) if j == ticks => {}
Some(_) => return Liveness::Dead, None => return Liveness::Unknown, }
match parse_state(stat) {
Some(b'Z') => match parse_num_threads(stat) {
Some(threads) if threads > 1 => Liveness::Alive,
Some(_) => Liveness::Dead,
None => Liveness::Unknown,
},
Some(b'X' | b'x') => Liveness::Dead,
Some(_) => Liveness::Alive,
None => Liveness::Unknown,
}
}
#[cfg(test)]
pub(crate) fn stat_fixture(state: &str, starttime: u64) -> Vec<u8> {
format!("1234 (myproc) {state} 1 1234 1234 0 -1 4194560 100 0 0 0 1 2 0 0 20 0 1 0 {starttime} 0 0").into_bytes()
}
#[cfg(test)]
#[path = "stat_parse_tests.rs"]
mod stat_parse_tests;