If your external process expects something on its stdin
, you MUST close the getOutputStream
. Otherwise you will waitFor
forever.
Here is the When Runtime.exec() won’t article from JavaWorld which describes different pitfalls of exec method and how to avoid them.
From my experience it’s better to consume STDOUT and STDERR of child process ( until they EOF ) and then block in waitFor
. Hopefully at this point you won’t have to waitFor long.
An answer to Kaleb’s question.
Under normal conditions you shouldn’t close the streams, however because you are waitingFor
and for whatever reason it does not have a timeout, you may need to close these streams if you encounter some error conditions in the output and don’t want to process child’s output further. However, whether the child program will terminate (crash) when it’s STDOUT or STDERR pipe is closed at the other end is totally up to that child’s implementation. Most shell programs though, will terminate under such conditions.
I really wish waitFor
had some meaningful timeout though and the Process
had a documented way of cleaning up its resources when you’ve decided to abandon its monitoring.