Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to stderr/stdout streams after Process.destroy() in Java?

Tags:

java

process

I'd like to have a timeout for a process I start from Java. After the timeout, I'd like to kill the process. So far, so good. Problem is, I want to capture stderr/stdout during both normal execution and after a timeout. What happens if I kill the process with destroy()? Can I retrieve the (partial) stderr/stdout produced so far? Or are they gone?

like image 236
Lajos Nagy Avatar asked Feb 27 '23 07:02

Lajos Nagy


2 Answers

Process handling is inherently OS-specific, I'm looking specifically at how Java handles Unix processes here.

It's unfortunate that Process closes its streams when you call .destroy(). I don't know why the JDK designers felt that was the right design pattern, but it certainly makes dealing with terminated processes more complicated.

It's worth noting that the InputStreams Process holds are instances of ProcessPipeInputStream which actually has a drainInputStream() method that does exactly what we'd want - it reads in any remaining bytes in the backing file descriptor and stores them in a byte buffer for us. This method is "called by the process reaper thread when the process exits", but unfortunately is not called when the process is TERM'ed by .destroy().

The best you can hope for then is to jury-rig your own drainInputStream() behavior and call that for both stdout and stderr before you call .destroy(). It's still possible for some data to being written to either stream after you drain them but before .destroy() finishes, but this will get most of it.

like image 161
dimo414 Avatar answered Mar 01 '23 20:03

dimo414


You should have one or two separate threads reading stdout and stderr (one if you merge them), apart from the thread that calls Process.exec()/waitFor()/destroy(). The reading thread(s) will get any data that is produced up to an EOF. If you call Process.destroy(), the EOF may happen sooner, that's all.

like image 20
user207421 Avatar answered Mar 01 '23 20:03

user207421