While running an external script, I want to read the ErrorStream and OutputStream of this script both simultaneously and separately and then process them further. Therefore, I start a Thread
for one of the streams. Unfortunately, the Process
doesn't seem to waitFor
the Thread
to be terminated, but return after the non-threaded stream has no further input.
In a nutshell, here is what I am doing:
ProcessBuilder pb = new ProcessBuilder(script);
final Process p = pb.start();
new Thread(new Runnable() {
public void run() {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
...read lines and process them...
}
}).start();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
...read lines and process them...
int exitValue = p.waitFor();
p.getOutputStream().close();
return exitValue;
Is there any possibility to waitFor
the Thread
to be terminated?
You can use Thread.join(...)
to wait for a Thread
to finish. Note that the call throws InterruptedException
if the current thread receives an interrupt before the thread you are waiting for finishes.