use crate::error::Result;
use anyhow::anyhow;
#[cfg(feature = "process")]
use sysinfo::{Pid, System};
pub fn get_current_pid() -> u32 {
std::process::id()
}
#[cfg(feature = "process")]
pub fn is_process_running(pid: u32) -> bool {
let mut sys = System::new_all();
sys.refresh_all();
sys.process(Pid::from(pid as usize)).is_some()
}
#[cfg(feature = "process")]
pub fn kill_process(pid: u32) -> Result<()> {
let mut sys = System::new_all();
sys.refresh_all();
if let Some(process) = sys.process(Pid::from(pid as usize)) {
if process.kill() {
Ok(())
} else {
Err(anyhow!("无法终止进程 {}", pid))
}
} else {
Err(anyhow!("找不到进程 {}", pid))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn current_pid_is_positive() {
let pid = get_current_pid();
assert!(pid > 0, "当前进程 PID 应 > 0,实际 {}", pid);
}
#[cfg(feature = "process")]
#[test]
fn own_process_is_running() {
assert!(
is_process_running(get_current_pid()),
"当前进程应被 sysinfo 识别为运行中"
);
}
#[cfg(feature = "process")]
#[test]
fn huge_pid_not_running() {
assert!(!is_process_running(u32::MAX - 1));
}
}