xtap-core-lib 0.5.2

星TAP实验室通用 Rust 基座:跨平台路径/IO/硬件/MCP HTTP 服务/egui 主题与字体(features 按需裁剪)
Documentation
use crate::error::Result;
use anyhow::anyhow;
#[cfg(feature = "process")]
use sysinfo::{Pid, System};

/// 获取当前进程 PID
pub fn get_current_pid() -> u32 {
    std::process::id()
}

/// 检查进程是否在运行 (需要 process feature)
#[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() {
        // 当前进程必然在运行(sysinfo 能查到自身)
        assert!(
            is_process_running(get_current_pid()),
            "当前进程应被 sysinfo 识别为运行中"
        );
    }

    #[cfg(feature = "process")]
    #[test]
    fn huge_pid_not_running() {
        // 一个不可能存在的 PID(u32 上限附近),不应被识别为运行中
        assert!(!is_process_running(u32::MAX - 1));
    }
}