src/tools/procfs.rs: start helper tools to read procfs

This commit is contained in:
Dietmar Maurer 2019-04-03 13:39:20 +02:00
parent 3489936ebb
commit 3c2012f97a
2 changed files with 49 additions and 0 deletions

View File

@ -31,6 +31,7 @@ pub mod fs;
pub mod tty;
pub mod signalfd;
pub mod daemon;
pub mod procfs;
mod process_locker;
pub use process_locker::*;

48
src/tools/procfs.rs Normal file
View File

@ -0,0 +1,48 @@
use failure::*;
use crate::tools;
use lazy_static::lazy_static;
use regex::Regex;
pub struct ProcFsPidStat {
pub status: u8,
pub utime: u64,
pub stime: u64,
pub starttime: u64,
pub vsize: u64,
pub rss: i64,
}
pub fn read_proc_pid_stat(pid: nix::unistd::Pid) -> Result<ProcFsPidStat, Error> {
let statstr = tools::file_read_firstline(format!("/proc/{}/stat", pid))?;
lazy_static! {
static ref REGEX: Regex = Regex::new(r"^(?P<pid>\d+) \(.*\) (?P<status>\S) -?\d+ -?\d+ -?\d+ -?\d+ -?\d+ \d+ \d+ \d+ \d+ \d+ (?P<utime>\d+) (?P<stime>\d+) -?\d+ -?\d+ -?\d+ -?\d+ -?\d+ 0 (?P<starttime>\d+) (?P<vsize>\d+) (?P<rss>-?\d+) \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ \d+ -?\d+ -?\d+ \d+ \d+ \d+").unwrap();
}
if let Some(cap) = REGEX.captures(&statstr) {
if pid != nix::unistd::Pid::from_raw(cap["pid"].parse::<i32>().unwrap()) {
bail!("unable to read pid stat for process '{}' - got wrong pid", pid);
}
return Ok(ProcFsPidStat {
status: cap["status"].as_bytes()[0],
utime: cap["utime"].parse::<u64>().unwrap(),
stime: cap["stime"].parse::<u64>().unwrap(),
starttime: cap["starttime"].parse::<u64>().unwrap(),
vsize: cap["vsize"].parse::<u64>().unwrap(),
rss: cap["rss"].parse::<i64>().unwrap() * 4096,
});
}
bail!("unable to read pid stat for process '{}'", pid);
}
pub fn read_proc_starttime(pid: nix::unistd::Pid) -> Result<u64, Error> {
let info = read_proc_pid_stat(pid)?;
Ok(info.starttime)
}