Suppose I have started a subprocess in Java, that may write to stdout and stderr:
Process subprocess = Runtime.getRuntime().exec(…);
I want to read all its stdout and stderr; or just ignore them.
If I do like this:
readAllFrom(subprocess.getInputStream()); //stdout is getInputStream, weird! readAllFrom(subprocess.getErrorStream()); //stderr
… it'll stuck, if subprocess first tries to output data to stderr and thus blocks at that point.
And if I do something like this:
while (…) { readLineFrom(subprocess.getInputStream()); readLineFrom(subprocess.getErrorStream()); }
… the risk, actually, seems to be the same.
If I do like this:
while (…) { nonblockingReadFrom(subprocess.getInputStream()); nonblockingReadFrom(subprocess.getOutputStream()); }
where
nonblockingReadFrom
can be something like:… nonblockingReadFrom(InputStream stream) { byte[] buffer = new byte[…]; stream.read(buffer, 0, Math.min(stream.available(), buffer.length)); … }
… it will make useless 100%-CPU-loads, if subprocess outputs data with some pauses.
Of course, I can create separate thread. Something like here (1, 2). But my question is about doing all in the same thread. Probably, something like Java interface to select system call is needed for that.
So, the question is: Is it possible to handle correctly stdout and stderr of a java.lang.Process
-typed subprocess in Java without using additional threads or temporary files?