title: Terminate process when timeout has been reached and process output in Rust
body: <p>I'm trying to consume output from a process in Rust. If the process doesn't terminate after a certain time, I want to terminate/kill it. Ideally I'd like to wrap everything in a generator so that I can iterate the output line by line, but I'm not experienced enough for that in Rust yet.</p>
  
  <p>Here's my code (<code>src/main.rs</code>), using the subprocess crate:</p>
  
  <pre class="lang-rust prettyprint-override"><code>use subprocess::{Popen, PopenConfig, Redirection};
  use std::io::Read;
  use std::time::Duration;
  
  
  fn main() {
      let mut p = Popen::create(&amp;["bash", "-c", "echo \"Hi There!\"; sleep 1000"], PopenConfig {stdout: Redirection::Pipe, ..Default::default()}, ).unwrap();
      let mut output = p.stdout.take().unwrap();
  
      let thread = std::thread::spawn(move || {
          let three_secs = Duration::from_secs(3);
          let one_sec = Duration::from_secs(1);
          let r = p.wait_timeout(three_secs).unwrap();
          match r {
              None =&gt; {
                  println!("Wait timed out, terminating process");
                  p.terminate().unwrap();
                  let r = p.wait_timeout(one_sec).unwrap();
                  match r {
                      None =&gt; {
                          println!("Termination didn't seem to work, killing");
                          p.kill().unwrap();
                      },
                      Some(_) =&gt; {
                          println!("Terminated process successfully");
                      },
                  }
                  p.wait().unwrap();},
              Some(_) =&gt; { println!("Process returned");},
          }
          println!("Everything fine");
      });
  
      println!("Starting to read output");
      let mut output_str = String::new();
      output.read_to_string(&amp;mut output_str).unwrap();
      println!("Done reading output");
      thread.join().unwrap();
  
      println!("Output: {}", output_str);
      println!("Hello, world!");
  }
  </code></pre>
  
  <p>I'd expect the following output:</p>
  
  <pre><code>Starting to read output
  Wait timed out, terminating process
  Terminated process successfully
  Everything fine
  Done reading output
  Output: Hi There!
  
  Hello, world!
  </code></pre>
  
  <p>and the process finishing after three seconds. But what I get is</p>
  
  <pre><code>Starting to read output
  Wait timed out, terminating process
  Terminated process successfully
  Everything fine
  </code></pre>
  
  <p>and the process doesn't terminate.</p>
  
  <p>For completeness, here is my <code>Cargo.toml</code> to go along with the <code>src/main.rs</code> from above:</p>
  
  <pre><code>[package]
  name = "subproc"
  version = "0.1.0"
  authors = ["&lt;snip&gt;"]
  edition = "2018"
  
  [dependencies]
  subprocess = "0.2.4"
  </code></pre>