use crate::cmd::cmd_error::CmdError;
use log::debug;
use std::process::{Child, Command};
pub fn execute(cmd: &str, args: &[&str]) -> Result<Vec<u8>, CmdError> {
debug!("executing command: {} {}", cmd, args.join(" "));
let output = Command::new(cmd)
.args(args)
.output()
.map_err(|e| CmdError::Execute(e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
return Err(CmdError::Run(stderr));
}
Ok(output.stdout)
}
pub fn is_process_alive(child: &mut Child) -> bool {
debug!("checking if process is alive: {}", child.id());
match child.try_wait() {
Ok(Some(_)) => false, Ok(None) => true, Err(_) => false, }
}
pub fn kill_process(mut child: Child) -> Result<(), Box<dyn std::error::Error>> {
debug!("killing process: {}", child.id());
child.kill()?;
child.wait()?;
Ok(())
}
pub fn kill_process_by_id(pid: u32) -> std::io::Result<()> {
debug!("killing process by id: {}", pid);
#[cfg(unix)]
{
Command::new("kill")
.arg("-9")
.arg(&pid.to_string())
.output()?;
}
#[cfg(windows)]
{
Command::new("taskkill")
.arg("/F")
.arg("/PID")
.arg(&pid.to_string())
.output()?;
}
Ok(())
}