views:

1718

answers:

4

My Java program uses ProcessBuilder (with redirectErrorStream set true) and has a loop that runs the processes's inputstream's read method, which is blocking. The external program I'm calling then comes to a stop waiting for input og stdin. I now want to kill the process. Is this not done by (in a seperate thread) calling the process's destroy method, and calling the inputstream's close method to stop the read method from blocking anymore, so that my initial thread can end its life.

For some reason process.getInputStream().close() blocks. From the JavaDoc I don't see why this can happen. Furthermore, I don't understand why the javadoc says "The close method of InputStream does nothing." (link to javadoc) Could someone explain this?

Thanks :-)

+1  A: 

For some reason process.getInputStream().close() blocks. From the JavaDoc I don't see why this can happen. Furthermore, I don't understand why the javadoc says "The close method of InputStream does nothing." (link to javadoc) Could someone explain this?

If you look at the Javadoc, you'll see that InputStream an abstract class. Subclasses that extend InputStream are expected to override the close() method (should it be needed). Clearly the InputStream subclass that you're using does something in the close method.

jdigital
of course, that makes good sense. I didn't notice that inputstream was abstract, thanks.
Allanrbo
+2  A: 

Regarding the blocking behavior, there is a known issue in Java that can cause deadlock when communicating with another process. I can't tell if this is what you're seeing but it's worth looking into. The document for java.lang.Process says:

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

jdigital
I'll look into that, thanks
Allanrbo
+1  A: 

Adding onto what jdigital wrote, check this article. It deals with Runtime.exec() method, and ProcessBuilder was introduced in Java 5, but it seems to me the discussion can be extrapolated to system processes in general.

javashlook
A: 

I think I figured this out. Obviously it is important to call process.getOutputStream().close() before process.getInputStream().close() and process.getErrorStream().close().

Allanrbo