tokio_process_bits/
lib.rs

1//! This crate is a collection of modules useful for working
2//! with Tokio when spawning off child processes.
3extern crate tokio_io;
4extern crate tokio_process;
5extern crate futures;
6extern crate tokio_core;
7
8use tokio_core::reactor::Handle;
9use tokio_process::CommandExt;
10use tokio_io::io::lines;
11use futures::Stream;
12use std::io::{BufReader, ErrorKind, Error};
13use std::process::Stdio;
14
15/// Hdl is a handler type combining the child future and
16/// stdout and stderr streams returned from the execute
17/// function.
18pub struct Hdl {
19    /// The child future. If this goes out of scope, the process will be killed.
20    /// Use the forget() method to avoid that.
21    pub child: ::tokio_process::Child,
22    /// Line based stream of child process' stdout
23    pub stdout: Box<Stream<Item = String, Error = Error>>,
24    /// Line based stream of child process' stderr
25    pub stderr: Box<Stream<Item = String, Error = Error>>,
26}
27
28// Create a new command from the given command and arguments and
29// spawn a child that runs the given command and returns line-by-line
30// streams of its stdout and stderr.
31pub fn execute<'a, I>(handle: &Handle, c: &str, args: I) -> Result<Hdl, Error>
32where
33    I: IntoIterator<Item = &'a str>,
34{
35    let mut cmd = ::std::process::Command::new(c);
36    cmd.args(args);
37
38    // We want to read stderr and stdout
39    cmd.stdout(Stdio::piped());
40    cmd.stderr(Stdio::piped());
41
42    // Spawn the child process
43    let mut child = try!(cmd.spawn_async(handle));
44
45    // Create line-based streams from stdout and stderr of child
46    let stdout_stream = match child.stdout().take() {
47        Some(reader) => Box::new(lines(BufReader::new(reader))),
48        None => return Result::Err(Error::new(ErrorKind::Other, "stdout ws not captured")),
49    };
50    let stderr_stream = match child.stderr().take() {
51        Some(reader) => Box::new(lines(BufReader::new(reader))),
52        None => return Result::Err(Error::new(ErrorKind::Other, "stderr ws not captured")),
53    };
54
55    let h = Hdl {
56        child: child,
57        stdout: stdout_stream,
58        stderr: stderr_stream,
59    };
60    Result::Ok(h)
61}