I use Java ProcessBuilder to run a subprocess, which is another Java program that needs to run in a separate JVM.
I am running two threads to read from stdout and stderr threads from Process, so there is no freeze if the stream buffers are full. A call to the Process.waitFor method returns, but the threads do not terminate.
The code I use looks something like (command - list of lines):
ProcessBuilder pb = new ProcessBuilder(command); final Process p = pb.start(); final ByteArrayOutputStream outStream = new ByteArrayOutputStream(); final ByteArrayOutputStream errStream = new ByteArrayOutputStream(); Thread outputThread = new Thread() { @Override public void run() { try { IOUtils.copy(p.getInputStream(), outStream); } catch (IOException e) { e.printStackTrace(); } }; }; outputThread.start(); Thread errorThread = new Thread() { @Override public void run() { try { IOUtils.copy(p.getErrorStream(), errStream); } catch (IOException e) { e.printStackTrace(); } }; }; errorThread.start(); int returncode = p.waitFor(); outputThread.join(); errorThread.join();
If I run something else, like "java -version" or "dir" or something else, the code works fine. I have access to the Java code I'm trying to run, but I never heard you call close () on System.out.
source share