Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ccccff
class StreamGobbler implements Runnable {
  private final InputStream is;
  private final PrintStream os;

  StreamGobbler(InputStream is, PrintStream os) {
    this.is = is;
    this.os = os;
  }

  public void run() {
    try {
      int c;
      while ((c = is.read()) != -1)
          os.print((char) c);
    } catch (IOException x) {
      // Handle error
    }
  }
}

public class Exec {
  public static void main(String[] args)
    throws IOException, InterruptedException {

    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("notemaker");

    // Any error message?
    Thread errorGobbler
      = new Thread(new StreamGobbler(proc.getErrorStream(), System.err));
 
    // Any output?
    Thread outputGobbler
      = new Thread(new StreamGobbler(proc.getInputStream(), System.out));

    errorGobbler.start();
    outputGobbler.start();

    // Any error?
    int exitVal = proc.waitFor();
    errorGobbler.join();   // Handle condition where the
    outputGobbler.join();  // process ends before the threads finish
  }
}

Exceptions

FIO07-J-EX0: Failure to supply input to a process that never reads input from its input stream is harmless and can be beneficial. Failure to empty the output or error streams of a process that never sends output to its output or error streams is similarly harmless or even beneficial. Consequently, programs are permitted to ignore the input, output, or error streams of processes that are guaranteed not to use those streams.

...