|
| 1 | +use nix::sys::signal::Signal; |
| 2 | +use sysinfo::Pid; |
| 3 | + |
| 4 | +pub fn terminate_process(pid: Pid) -> Result<(), String> { |
| 5 | + let nix_pid = nix::unistd::Pid::from_raw(pid.as_u32() as i32); |
| 6 | + nix::sys::signal::kill(nix_pid, Signal::SIGTERM).map_err(|e| format!("Failed to terminate process: {}", e)) |
| 7 | +} |
| 8 | + |
| 9 | +#[cfg(test)] |
| 10 | +#[cfg(not(windows))] |
| 11 | +mod tests { |
| 12 | + use std::process::Command; |
| 13 | + use std::time::Duration; |
| 14 | + |
| 15 | + use super::*; |
| 16 | + |
| 17 | + // Helper to create a long-running process for testing |
| 18 | + fn spawn_test_process() -> std::process::Child { |
| 19 | + let mut command = Command::new("sleep"); |
| 20 | + command.arg("30"); |
| 21 | + command.spawn().expect("Failed to spawn test process") |
| 22 | + } |
| 23 | + |
| 24 | + #[test] |
| 25 | + fn test_terminate_process() { |
| 26 | + // Spawn a test process |
| 27 | + let mut child = spawn_test_process(); |
| 28 | + let pid = Pid::from_u32(child.id()); |
| 29 | + |
| 30 | + // Terminate the process |
| 31 | + let result = terminate_process(pid); |
| 32 | + |
| 33 | + // Verify termination was successful |
| 34 | + assert!(result.is_ok(), "Process termination failed: {:?}", result.err()); |
| 35 | + |
| 36 | + // Give it a moment to terminate |
| 37 | + std::thread::sleep(Duration::from_millis(100)); |
| 38 | + |
| 39 | + // Verify the process is actually terminated |
| 40 | + match child.try_wait() { |
| 41 | + Ok(Some(_)) => { |
| 42 | + // Process exited, which is what we expect |
| 43 | + }, |
| 44 | + Ok(None) => { |
| 45 | + panic!("Process is still running after termination"); |
| 46 | + }, |
| 47 | + Err(e) => { |
| 48 | + panic!("Error checking process status: {}", e); |
| 49 | + }, |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + #[test] |
| 54 | + fn test_terminate_nonexistent_process() { |
| 55 | + // Use a likely invalid PID |
| 56 | + let invalid_pid = Pid::from_u32(u32::MAX - 1); |
| 57 | + |
| 58 | + // Attempt to terminate a non-existent process |
| 59 | + let result = terminate_process(invalid_pid); |
| 60 | + |
| 61 | + // Should return an error |
| 62 | + assert!(result.is_err(), "Terminating non-existent process should fail"); |
| 63 | + } |
| 64 | +} |
0 commit comments