1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use std::path::Path;
use std::str::FromStr;
use heim_common::prelude::*;
use heim_common::utils::parse::ParseIterator;
use crate::{Pid, ProcessState};
#[derive(Debug)]
pub struct Stat {
pid: Pid,
name: String,
state: ProcessState,
ppid: Pid,
}
impl FromStr for Stat {
type Err = Error;
fn from_str(s: &str) -> Result<Stat> {
let mut parts = s.splitn(2, ' ');
let pid: Pid = parts.try_from_next()?;
let rest = parts.next().ok_or(Error::new(ErrorKind::Parse))?;
let name_end = rest.chars().enumerate().skip(1).position(|(_, c)| c == ')')
.ok_or_else(|| Error::new(ErrorKind::Parse))?;
let name = rest[1..name_end + 1].to_string();
let mut parts = rest[name_end + 3..].split_whitespace();
let state: ProcessState = parts.try_from_next()?;
let ppid: Pid = parts.try_from_next()?;
Ok(Stat {
pid,
name,
state,
ppid,
})
}
}
impl Stat {
pub fn from_path<T>(path: T) -> impl Future<Item=Stat, Error=Error>
where T: AsRef<Path> + Send + 'static {
utils::fs::read_into(path)
}
pub fn pid(&self) -> Pid {
self.pid
}
pub fn name(&self) -> &str {
self.name.as_str()
}
pub fn state(&self) -> ProcessState {
self.state
}
pub fn ppid(&self) -> Pid {
self.ppid
}
}
impl FromStr for ProcessState {
type Err = Error;
fn from_str(s: &str) -> Result<Self> {
let res = match s {
"R" => ProcessState::Running,
"S" => ProcessState::Sleeping,
"D" => ProcessState::DiskSleep,
"Z" => ProcessState::Zombie,
"T" => ProcessState::Stopped,
"t" => ProcessState::TracingStop,
"X" | "x" => ProcessState::Dead,
"K" => ProcessState::WakeKill,
"W" => ProcessState::Waking,
"P" => ProcessState::Parked,
"I" => ProcessState::Idle,
other => unreachable!("Unknown process state {}", other)
};
Ok(res)
}
}