1use crate::error::Result;
2use anyhow::anyhow;
3#[cfg(feature = "process")]
4use sysinfo::{Pid, System};
5
6pub fn get_current_pid() -> u32 {
8 std::process::id()
9}
10
11#[cfg(feature = "process")]
13pub fn is_process_running(pid: u32) -> bool {
14 let mut sys = System::new_all();
15 sys.refresh_all();
16 sys.process(Pid::from(pid as usize)).is_some()
17}
18
19#[cfg(feature = "process")]
21pub fn kill_process(pid: u32) -> Result<()> {
22 let mut sys = System::new_all();
23 sys.refresh_all();
24 if let Some(process) = sys.process(Pid::from(pid as usize)) {
25 if process.kill() {
26 Ok(())
27 } else {
28 Err(anyhow!("无法终止进程 {}", pid))
29 }
30 } else {
31 Err(anyhow!("找不到进程 {}", pid))
32 }
33}
34
35#[cfg(test)]
36mod tests {
37 use super::*;
38
39 #[test]
40 fn current_pid_is_positive() {
41 let pid = get_current_pid();
42 assert!(pid > 0, "当前进程 PID 应 > 0,实际 {}", pid);
43 }
44
45 #[cfg(feature = "process")]
46 #[test]
47 fn own_process_is_running() {
48 assert!(
50 is_process_running(get_current_pid()),
51 "当前进程应被 sysinfo 识别为运行中"
52 );
53 }
54
55 #[cfg(feature = "process")]
56 #[test]
57 fn huge_pid_not_running() {
58 assert!(!is_process_running(u32::MAX - 1));
60 }
61}