Skip to main content

autocore_std/
diagnostics.rs

1//! Lightweight process diagnostics via `/proc/self`.
2//!
3//! These helpers are designed for periodic logging inside real-time loops.
4//! They perform a single read per call and are cheap on Linux.
5
6/// Count open file descriptors by reading `/proc/self/fd`.
7pub fn count_open_fds() -> usize {
8    std::fs::read_dir("/proc/self/fd").map(|d| d.count()).unwrap_or(0)
9}
10
11/// Return resident set size in KiB by reading `/proc/self/statm`.
12///
13/// The second field of `statm` is RSS in pages. We multiply by the page
14/// size (almost always 4 KiB on Linux).
15pub fn get_rss_kb() -> u64 {
16    let page_kb: u64 = 4; // 4096 / 1024
17    std::fs::read_to_string("/proc/self/statm")
18        .ok()
19        .and_then(|s| {
20            s.split_whitespace()
21                .nth(1) // RSS field (in pages)
22                .and_then(|v| v.parse::<u64>().ok())
23        })
24        .map(|pages| pages * page_kb)
25        .unwrap_or(0)
26}