Skip to main content

xtap_core_lib/
process.rs

1use crate::error::Result;
2use anyhow::anyhow;
3#[cfg(feature = "process")]
4use sysinfo::{Pid, System};
5
6/// 获取当前进程 PID
7pub fn get_current_pid() -> u32 {
8    std::process::id()
9}
10
11/// 检查进程是否在运行 (需要 process feature)
12#[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/// 杀掉进程
20#[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}