Java Runtime exec can hang

The next version of Savant is going to focus heavily on the stand-alone runtime and support for dialects and plugins. Supporting all that is largely handled by using a simple executor framework I wrote around Java 1.4 and lower’s Runtime.exec method. A few things to keep in mind when using this:

  1. Always read from the streams prior to calling waitFor. Otherwise you could end up waiting forever on Windows and other OS platforms whose I/O buffers can’t store enough from standard out and standard error to ensure the program has finished. These platforms will pause the execution of whatever is running until something reads the buffered content from standard out and standard error. I would imagine all platforms suffer from this, but some platforms have larger buffers than others. Needless to say, always read from the streams first.
  2. Always read from standard error first. I ran across a bug where some OS platforms will always open standard out, but never close it. What this means is that if you read from standard out first and the process only writes to standard error, you’ll hang forever waiting to read. If you read from standard error first, you’ll always be okay on these platforms because the OS seems to shutdown standard error. I think however, that the best way to handle all cases is to check both standard error and standard out for readiness and only read from them if they have something to offer. The downside I could see here is that error isn’t ready, but eventually will be.

3 thoughts on “Java Runtime exec can hang

  1. i am have a problem with a process that accepts a input.. wat happens if I use runtime to call a command which requires an input … well in my case it hangs .. any workarrounds ?


  2. my problem is:
    a shell file named at /home/huanghao/test/Demo dir in my linux system, and i want using Runtime class to invoke it, so i define a
    String[] cmd = new String{“sh”, “-c”, path}; /*path is /home/huanghao/test/Demo/*/
    and then use Runtime.getRuntime().exec(cmd);
    but it seems not work, the shell file isn’t run at all?
    can you tell me what’s my problem is?
    the whole function code is below:


  3. I’m not sure exactly what the issue is, but if you read the error stream, you might figure it out. You could also output the result code and then look at the ‘sh’ manpage to see what that result code means. Lastly, have you tried using the path ‘/bin/sh’ for the executable?


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s