1use std::io;
2use std::process::Command as CommandSys;
3
4pub fn kill_by_pid(pid: i64) -> io::Result<()> {
6 let mut cmd = build_kill_command(true, std::iter::once(pid), None);
7
8 let output = cmd.output()?;
9
10 if !output.status.success() {
11 return Err(io::Error::other("failed to kill process"));
12 }
13
14 Ok(())
15}
16
17pub fn build_kill_command(
20 force: bool,
21 pids: impl Iterator<Item = i64>,
22 signal: Option<u32>,
23) -> CommandSys {
24 if cfg!(windows) {
25 let mut cmd = CommandSys::new("taskkill");
26
27 if force {
28 cmd.arg("/F");
29 }
30
31 for id in pids {
34 cmd.arg("/PID");
35 cmd.arg(id.to_string());
36 }
37
38 cmd
39 } else {
40 let mut cmd = CommandSys::new("kill");
41 if let Some(signal_value) = signal {
42 cmd.arg(format!("-{}", signal_value));
43 } else if force {
44 cmd.arg("-9");
45 }
46
47 cmd.args(pids.map(move |id| id.to_string()));
48
49 cmd
50 }
51}