How can I obtain a process' output while setting a timeout value?
I am currently using Apache Commons IO utils to create a string from the process' standard and error outputs.
The code below, as is (with the comments), works fine for processes that terminate. However, if the process doesn't terminate, the main thread doesn't terminate either!
If I uncomment out the commented code and instead comment out process.waitfor()
, the method will properly destroy non terminating processes. However, for terminating processes, the output isn't properly obtained. It appears that once waitFor
is completed, I cannot get the process' input and error streams?
Finally, if I attempt to move the commented section to where process.waitFor()
currently is, remove process.waitFor()
and uncomment the commented section, then for non terminating processes, the main thread also won't stop. This is because the process.waitFor(15, ...)
will never be reached.
private static Outputs runProcess(String command) throws Exception {
Process process = Runtime.getRuntime().exec(command);
// if (!process.waitFor(15, TimeUnit.SECONDS)) {
// System.out.println("Destroy");
// process.destroy();
// }
// Run and collect the results from the standard output and error output
String stdStr = IOUtils.toString(process.getInputStream());
String errStr = IOUtils.toString(process.getErrorStream());
process.waitFor();
return new Outputs(stdStr, errStr);
}