javaruntime.exec

Why process.waitFor() is not returning?


I'm trying to execute task with Runtime.getRuntime().exec.

As expected

I am getting "task started" in console. And the task gets executed and was completed.

Issue

Never got "task completed" printed.

Do you know what could be the reason? or How can I handle?

Code

System.out.println("task started");
Process process = Runtime.getRuntime().exec("cmd.exe /c task.bat task.job");
process.waitFor();
System.out.println("task completed");

Why is process.waitFor() not returning?


Solution

  • The exec command is returning a process-handle (like the PID).

    If the process has already terminated, you can query its exit-value with process.exitValue() as int:

    By convention, the value 0 indicates normal termination.

    otherwise if the process is still running:

    IllegalThreadStateException - if the subprocess represented by this Process object has not yet terminated

    Same for waitFor():

    This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.

    Since the blocking is not what you probably want, can set a timeout here, then return of waitFor(long, TimeUnit) changes.

    So you can wrap in a try-catch block to get complete control:

    Process process = null;
    System.out.println("Task will start soon ..");
    try {
        process = Runtime.getRuntime().exec("cmd.exe /c task.bat task.job");
        System.out.println("Task started.");
        boolean alreadyTerminated = process.waitFor(50L, TimeUnit.SECONDS);  // you can also set a timeout
        if (!alreadyTerminated)
            System.out.println("Task still executing. Will wait for 50 seconds.");
        int exitValue = process.exitValue();
        System.out.println("Task completed with exit-code: " + exitValue);
    } catch (IllegalThreadStateException e) {
        System.out.println(e);
    }