title: Run external program from Java, read output, allow interruption
body: <p>I want to launch a process from Java, read its output, and get its return code. But while it's executing, I want to be able to cancel it. I start out by launching the process:</p>
  
  <pre><code>ProcessBuilder pb = new ProcessBuilder(args);
  pb.redirectErrorStream(true);
  Process proc = pb.start();
  </code></pre>
  
  <p>If I call proc.waitFor(), I can't do anything until the process exits. So I'm assuming I need to something like this:</p>
  
  <pre><code>while (true) {
    see if process has exited
    capture some output from the process
    decide if I want to cancel it, and if so, cancel it
    sleep for a while
  }
  </code></pre>
  
  <p>Is this right? Can someone give me an example of how to do this in Java?</p>