Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java determine if a process created using Runtime environment has finished execution?

Runtime.getRuntime.exex("abc.exe -parameters");

using .waitFor() does not help to determine the completion of process.

like image 932
devashish jasani Avatar asked Jul 29 '11 13:07

devashish jasani


2 Answers

Looks like JDK8 introduces Process.isAlive(). Surprised it took so long...

In the meantime, the best option seems to be to poll Process.exitValue(), wrapped in a try-catch:

// somewhere previous...
String[] cmd = { "abc.exe", "-p1", "-p2" };
Process process = Runtime.getRuntime.exec(cmd);

// call this method repeatedly until it returns true
private boolean processIsTerminated () {
    try {
        process.exitValue();
    } catch (IllegalThreadStateException itse) {
        return false;
    }
    return true;
}

Alternately, a similar method could return the exit value if the process had terminated, or some other specified value if not.

like image 112
ericsoco Avatar answered Oct 20 '22 00:10

ericsoco


Process.waitFor() (javadoc) should work. If it doesn't work then either:

  • there's a bug in the JVM or the OS (highly unlikely for something like this), or

  • there is something about the process and/or your Java code that means that the process won't exit.


In current releases of Java you can also use Process.isAlive (javadoc) to test the process status without blocking until it finishes. For Java 7 and older there is a hacky solution that entails polling the process return code and catching an exception, but this is inefficient. You should upgrade to Java 8 or later as soon as possible!


Once the task is finished its goes for an indefinite wait. (I don't know why).

If this happening, then neither waitFor() or isAlive() will help.

The most likely reasons that a process launched from Java won't / can't exit are:

  • the process is blocked waiting for your Java application to give it some input (via its stdin),

  • the process is blocked waiting for your Java application to read its output (i.e. its stdout or stderr),

  • it is blocked waiting on some external event; e.g. if it is trying to talk remote server that is not responding,

  • something has sent it a STOP signal of some kind, or

  • it is just taking a looong time to run.

The first two of these reasons / causes can be addressed by (respectively) closing the Java output stream connected to its standard input, and reading (and possibly discarding) the Java input streams connected to its standard output and standard error. The other causes are intractable, and your only options are to "wait it out" or attempt to kill off the process.


Bottom line - you need to find out why your process isn't completing. The blocked Process.waitFor() call is a symptom, not the disease.

like image 32
Stephen C Avatar answered Oct 20 '22 00:10

Stephen C