1

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

1
  • Chances are you need to do a bit of both: you need to have a thread that reads the standard output of the process (you can throw away the contents) and you need a thread that waits for the process to finish or 5 hours using 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 in input.readLine() until it outputs a line. Commented Jun 15, 2015 at 14:12

1 Answer 1

2

I think the problem may be with the BufferedReader. Are you trying to use the BufferedReader to get inptut? If so, use the Scanner class.

Sign up to request clarification or add additional context in comments.

1 Comment

I could solve a deadlock because of BufferedReader.readLine or InputStreamReader.read blocking forever after the underlying process has been destroyed by reading with while(process.isAlive()) {while(scanner.hasNext()) {String line = scanner.nextLine();}} on different threads for both stdout and stderr.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.