title: When calling Runtime.getRuntime().exec() in a loop, how can I get each invocation to produce output instead of just the first?
body: <p>I am writing a process that will run continuously, getting messages on a queue which cause it to call an executable and process its output. I am using Runtime.getRuntime().exec() to invoke it, but I am only getting output the first time.  To more easily show the issue, I have put it in a loop.  I am using 'seq 1 5' as a standin for the executable, which will print the numbers 1 to 5 each on a separate line.  (I have run it on both Mac 10.7 and Fedora 14.)</p>
  
  <pre><code>    public static void main(String args[]) {
      for (int i = 0; i &lt; 4; i++) {
          try {
              Process process = Runtime.getRuntime().exec("seq 1 5");
              BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
              BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
              while (reader.ready() || errReader.ready()) {
                  if (reader.ready()) {
                      System.out.println("Process output: " + reader.readLine());
                  }
                  if (errReader.ready()) {
                      System.err.println("Process error: " + errReader.readLine());
                  }
              }
              reader.close();
              errReader.close();
              int result = process.waitFor();
              if (result != 0) {
                  System.err.println("Process returned with result " + 0);
              }
              System.out.println("Finished process for iteration " + i);
          } catch (IOException e) {
              e.printStackTrace();
          } catch (InterruptedException e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>Here is the result - you can see the expected output of the process only occurs in the first loop:</p>
  
  <pre><code>Process output: 1
  Process output: 2
  Process output: 3
  Process output: 4
  Process output: 5
  Finished process for iteration 0
  Finished process for iteration 1
  Finished process for iteration 2
  Finished process for iteration 3
  </code></pre>
  
  <p>Occasionally, perhaps one out of 10 runs, one of the later iterations will print output as well - but never all of them. Obviously there must be something that doesn't get cleaned up correctly, hence causing all but the first exec() to misbehave, but I don't know what it could be.  The input streams both get closed.</p>