0

I have the java application which starts external process through process builder.

External application interracts with rest "world" through stdin,stdout,stderr. Also this process should not be executed longer than some timeout.

code looks like this:

ProcessBuilder pb = new ProcessBuilder(parameters);
Process process = pb.start();
OutputStream processOutputStream = process.getOutputStream();
IOUtils.write(inputJson, processOutputStream); // write data to external process
processOutputStream.close(); we don't need pass more arguments

InputStream errorStream = process.getErrorStream();

boolean responseWithinTimeout = process.waitFor(2000, TimeUnit.MILLISECONDS); //app should work not longer than 2 sec
if (process.isAlive()) {
    process.destroyForcibly();
}
String stringFromErrorStream = IOUtils.toString(errorStream, "UTF-8"); //read from external application error stream

My questions:

  1. Does 2000 niliseconds starts sincepb.start() or since process.waitFor
  2. Is it correct to read from errorStream when application already killed or it should be placed before process.destroyForcibly()?
gstackoverflow
  • 36,709
  • 117
  • 359
  • 710
  • It should be noticed that the process started won't end if either of STDIN or STDERR is not empty. This must have been mentioned somewhere on SO. – glee8e Mar 31 '17 at 08:43
  • @glee8e What do you want to say? My application stop normally – gstackoverflow Mar 31 '17 at 09:07
  • In most times the process should be forcibly killed because of that holy timeout, not gracefully ended. See http://stackoverflow.com/a/3285479/5818889 – glee8e Mar 31 '17 at 11:36

1 Answers1

0

Does 2000 milliseconds starts sincepb.start()

No.

or since process.waitFor()

Yes.

Is it correct to read from errorStream when application already killed

No.

or it should be placed before process.destroyForcibly()?

Yes. Best in a separate thread. You should also consume the process's stdout. Otherwise it can block.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • Can you argue last comment?(why stream should be read before process destroy and why stdout should be consumed (I don't understand why it can be blocked)) – gstackoverflow Mar 31 '17 at 09:54