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

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

sblundy
  • 60,628
  • 22
  • 121
  • 123
devashish jasani
  • 413
  • 1
  • 4
  • 15
  • What is the problem with waitFor()? – Hunter McMillen Jul 29 '11 at 13:30
  • [`waitFor`](http://download.oracle.com/javase/6/docs/api/java/lang/Process.html#waitFor%28%29) documentation says it returns if the process is terminated. The return value is the exit value of the process. waitFor also throws an InterruptException if interruption occurs. Can you share what behavior you expect from process `abc.exe`? You may need to capture the output or error streams. – Atreys Jul 29 '11 at 13:31
  • 1
    Can you state why `waitFor()` does not help you in this case? Your statement is at odds with the documentation, and I would trust the documentation not a random stranger on the Internet. – Vineet Reynolds Jul 29 '11 at 13:35
  • the abc.exe file encodes messages from one file to other.Once the task is finished its goes for an indefinite wait(i dont know why?). – devashish jasani Jul 29 '11 at 13:56
  • @devashish If the behavior of the abc.exe process is to do something and then waste time doing nothing, than your process is not going to terminate and waitFor will keep waiting for it. Given this information the answer to the title question is that the process has never finished. An assumption can be made that either abc.exe is broken or misunderstood. – Atreys Jul 29 '11 at 14:10

4 Answers4

18

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.

ericsoco
  • 24,913
  • 29
  • 97
  • 127
  • 1
    Ok, thanks. I thought exceptions are not supposed to be used for normal code path. But if it's the only way... we won't be porting to JDK8 for a long time yet. – John Henckel Sep 30 '14 at 15:22
  • @JohnHenckel - Hopefully you have done it by now. Java 7 has been EOL for 4 years now (and counting ....) – Stephen C May 06 '19 at 03:29
10

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.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

I have a similar issue and neither of the methods written here works for me. This is my code:

public void startCCleaner() {
    System.out.println("Starting ccleaner...");
    try {
        Process process = new ProcessBuilder("C:\\Program Files\\CCleaner\\CCleaner64.exe").start();
        if(process.waitFor() == 0 ){
            System.out.println("Process terminated ");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
Essej
  • 892
  • 6
  • 18
  • 33
0

If you don't want to use waitFor(), which apparently you don't you can always test the exit value directly.

import java.util.*;
import java.io.*;
public class ProcExitTest
{
    public static void main(String args[])
    {
        try
        {            
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("<....>");
            int exitVal = proc.exitValue();
            System.out.println("Process exitValue: " + exitVal);
        } 
          catch (InterruptedException ie)
          {
            ie.printStackTrace();
          }
    }
}

exit code 0 means normal termination.

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170
  • Are you expecting something to be thrown? perhaps from [exitValue](http://download.oracle.com/javase/6/docs/api/java/lang/Process.html#exitValue%28%29)? – Atreys Jul 29 '11 at 13:48
  • This is something I copied from a file I had open. It can still catch the exception, as they are 'Throwable' objects. But I suppose ill edit it to avoid the slew of downvotes – Hunter McMillen Jul 29 '11 at 14:03
  • Certainly, but as there is no mechanism for allowing the process to finish in your code, the call to exitValue is likely to produce an exception. – Atreys Jul 29 '11 at 14:06
  • This was just an example of how the OP could test the exit value, since that is what they said they were looking for. I would never use this in a program, it's an awful piece of code – Hunter McMillen Jul 29 '11 at 14:07