use async_io::Timer;
use async_process::{Command, Stdio};
use futures_lite::{future, prelude::*};
use std::io;
fn main() -> io::Result<()> {
async_io::block_on(async {
let mut child = Command::new("sleep")
.arg("3")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let mut stdout = String::new();
let drain_stdout = {
let buffer = &mut stdout;
let mut stdout = child.stdout.take().unwrap();
async move {
stdout.read_to_string(buffer).await?;
future::pending().await
}
};
let mut stderr = String::new();
let drain_stderr = {
let buffer = &mut stderr;
let mut stderr = child.stderr.take().unwrap();
async move {
stderr.read_to_string(buffer).await?;
future::pending().await
}
};
let wait = async move {
child.status().await?;
io::Result::Ok(false)
};
let timeout_s = 1;
let timeout = async move {
Timer::after(std::time::Duration::from_secs(timeout_s)).await;
Ok(true)
};
let timed_out = drain_stdout.or(drain_stderr).or(wait).or(timeout).await?;
if timed_out {
println!("The child timed out.");
} else {
println!("The child exited.");
}
println!("Stdout:\n{stdout}");
println!("Stderr:\n{stderr}");
Ok(())
})
}