Java Reference
In-Depth Information
If we modify the program to invoke this method prior to waiting for the slave process, the program
prints 0 as expected:
} else {
// Master
Process process = Runtime.getRuntime().exec(COMMAND);
drainInBackground(process.getInputStream());
int exitValue = process.waitFor();
System.out.println(exitValue);
}
The lesson is that you must drain the output stream of a child process in order to ensure its
termination; the same goes for the error stream , which can be even more troublesome because
you can't predict when a process will dump lots of output to it. In release 5.0, a class named
ProcessBuilder was added to help you drain these streams. Its redirectErrorStream method
merges the streams so you have to drain only one. If you elect not to merge the output and error
streams, you must drain them concurrently. Attempting to drain them sequentially can cause the
child process to hang.
Many programmers have been bitten by this bug over the years. The lesson for API designers is that
the Process class should have prevented this problem, perhaps by draining the output and error
streams automatically unless the client expressed intent to read them. More generally, APIs should
make it easy to do the right thing and difficult or impossible to do the wrong thing .
< Day Day Up >
 
 
Search WWH ::




Custom Search