use sysinfo::{
CpuRefreshKind, MemoryRefreshKind, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind,
};
use super::info::ProcessInfo;
#[derive(Debug, Clone, Default)]
pub struct SystemStats {
pub cpu_usage: f32,
pub total_memory: u64,
pub used_memory: u64,
pub total_swap: u64,
pub used_swap: u64,
pub cpu_count: usize,
}
pub struct ProcessScanner {
system: System,
}
fn refresh_kind() -> ProcessRefreshKind {
ProcessRefreshKind::nothing()
.with_cpu()
.with_memory()
.with_exe(UpdateKind::OnlyIfNotSet)
.with_cmd(UpdateKind::OnlyIfNotSet)
.with_cwd(UpdateKind::OnlyIfNotSet)
.with_environ(UpdateKind::OnlyIfNotSet)
}
impl ProcessScanner {
pub fn new() -> Self {
let mut system = System::new();
system.refresh_processes_specifics(ProcessesToUpdate::All, true, refresh_kind());
system.refresh_cpu_specifics(CpuRefreshKind::nothing().with_cpu_usage());
Self { system }
}
pub fn refresh(&mut self) -> (Vec<ProcessInfo>, SystemStats) {
self.system
.refresh_processes_specifics(ProcessesToUpdate::All, true, refresh_kind());
self.system
.refresh_cpu_specifics(CpuRefreshKind::nothing().with_cpu_usage());
self.system
.refresh_memory_specifics(MemoryRefreshKind::everything());
let processes = self
.system
.processes()
.iter()
.map(|(&pid, proc)| ProcessInfo::from_sysinfo(pid, proc))
.collect();
let stats = SystemStats {
cpu_usage: self.system.global_cpu_usage(),
total_memory: self.system.total_memory(),
used_memory: self.system.used_memory(),
total_swap: self.system.total_swap(),
used_swap: self.system.used_swap(),
cpu_count: self.system.cpus().len(),
};
(processes, stats)
}
}
impl Default for ProcessScanner {
fn default() -> Self {
Self::new()
}
}