Alex Rivera | Logout

Process.waitFor(), threads, and InputStreams

Asked 2010-01-27T22:19:47.900
33

In pseudocode, here's what I'm doing:

Process proc = runtime.exec(command);
processOutputStreamInThread(proc.getInputStream());
processOutputStreamInThread(proc.getErrorStream());
proc.waitFor()

However, sometimes processOutputStreamInThread doesn't see any output and sometimes it does. Roughly, the method creates a BufferedInputStream of the command's output and sends it to a logger.

Based on what I'm seeing, I'm guessing that command need not have all it's output dumped into the streams fed by getInputStream() and getErrorStream(), thus allowing the stream to be empty.

The results of my trials are the following questions:

(1) Does waitFor() in java.lang.Process require the executed program's output to have been read before it returns?

The documentation only states:

causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

(2) Under what conditions do the streams provided by getInputStream and getErrorStream need to be closed and/or are they closed automatically?

The documentation only states:

Gets the error stream of the subprocess. The stream obtains data piped from the error output stream of the process represented by this Process object.

Implementation note: It is a good idea for the input stream to be buffered.

One user re

Edit
Report

1 Answer

2

I think this is slightly counter-intuitive, but:

getOutputStream Gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by this Process object. Implementation note: It is a good idea for the output stream to be buffered. Returns: the output stream connected to the normal input of the subprocess.

I read that as this Output stream from the main process and is attached to the standard input of the sub-process, so when you write to getOutputStream().write() you are actually writing on the stdin.

Do you possibly want to use .getInputStream()?

Returns: the input stream connected to the normal output of the subprocess.

As for Process.Waitfor() the API docs say:

causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

I would say the thread this is called in will be blocked until such a time as the process has finished executing - you may still be processing output at this stage depending on the other threads or they may have finished before your thread returns.

answered 2010-01-27T22:41:30.720

Your Answer