My OS is Windows 8.1 64 bit I need to read process output, but if it works more than 5 hours, I should destroy the process. So, there are two ways: 1) process works < 5 hours and it ends by itself; 2) it if works >= 5 hours, after that time I destroy it. I had two variants:
1.
ProcessBuilder pb = new ProcessBuilder(corePath.getAbsolutePath(), ... );
Process core = pb.start();
if(!core.waitFor(5, TimeUnit.HOURS))
{
System.out.println("Process destroyed, path " + root.getAbsolutePath());
core.destroy();
}
String output = IOUtils.toString(core.getInputStream());
return output;
2.
Process core = pb.start();
StringBuilder sb = new StringBuilder();
BufferedReader input = new BufferedReader(new InputStreamReader(core.getInputStream()));
String line;
while(System.currentTimeMillis() < end && (line = input.readLine()) != null)
{
sb.append(line);
}
input.close();
Problems: 1) program was waiting exactly 5 hours (even if process should be finished in few seconds) 2) program is waiting until the process is end
May someone advise another way to handle this? Thanks
Process.waitFor(). The reason for this is that with 1 the process might block, waiting for you to read out its output buffer, while with 2 your application will block, waiting indefinitely ininput.readLine()until it outputs a line.