use std::process::{Command, Output, Stdio};
use std::time::{Duration, Instant};
pub fn command_output_timeout(program: &str, args: &[&str], timeout: Duration) -> Option<Output> {
let mut child = Command::new(program)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.ok()?;
let deadline = Instant::now() + timeout;
loop {
match child.try_wait() {
Ok(Some(_)) => return child.wait_with_output().ok(),
Ok(None) => {
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
return None;
}
std::thread::sleep(Duration::from_millis(10));
}
Err(_) => {
let _ = child.kill();
let _ = child.wait();
return None;
}
}
}
}