1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::io::prelude::*;
pub(crate) fn wait_with_input_output(
mut child: std::process::Child,
input: Option<&[u8]>,
timeout: Option<std::time::Duration>,
) -> std::io::Result<std::process::Output> {
let input = input.map(|b| b.to_owned());
let stdin = input.and_then(|i| {
child
.stdin
.take()
.map(|mut stdin| std::thread::spawn(move || stdin.write_all(&i)))
});
fn read<R>(mut input: R) -> std::thread::JoinHandle<std::io::Result<Vec<u8>>>
where
R: Read + Send + 'static,
{
std::thread::spawn(move || {
let mut ret = Vec::new();
input.read_to_end(&mut ret).map(|_| ret)
})
}
let stdout = child.stdout.take().map(read);
let stderr = child.stderr.take().map(read);
stdin.and_then(|t| t.join().unwrap().ok());
let status = if let Some(timeout) = timeout {
wait_timeout::ChildExt::wait_timeout(&mut child, timeout)
.transpose()
.unwrap_or_else(|| {
let _ = child.kill();
child.wait()
})
} else {
child.wait()
}?;
let stdout = stdout
.and_then(|t| t.join().unwrap().ok())
.unwrap_or_default();
let stderr = stderr
.and_then(|t| t.join().unwrap().ok())
.unwrap_or_default();
Ok(std::process::Output {
status,
stdout,
stderr,
})
}