Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
public class Exec {
  public static void main(String args[]) {
    try {
      Runtime rt = Runtime.getRuntime();
      Process proc = rt.exec("notemaker");
      int exitVal = proc.waitFor();
    } catch (Throwable t) { t.printStackTrace();}
  }
}

Compliant Solution (1)

An inefficient solution would be to exhaust the output (or stderr) stream before beginning to wait for the process. A better option is to empty both the stderr and output streams. The code below shows this but is not the best solution since it does not process any arguments passed to the external program (notemaker) and in turn exits with an OS-specific non-zero exit code.

Code Block
bgColor#ccccff
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

public class Exec {
  public static void main(String args[]) {
    try {
      Runtime rt = Runtime.getRuntime();
      Process proc = rt.exec("notemaker");
      InputStream is = proc.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      String line;

      while ( (line = br.readLine()) != null)   
        System.out.println(line);  // prints the error lines

      int exitVal = proc.waitFor();
    } catch (Throwable t) { t.printStackTrace(); }
  }
}

Compliant Solution (2)

The second compliant solution spawns a command interpreter and executes the user supplied command. It uses a separate OutputStream to write the output that is read in from the external process.

...