NullPointerException
NullPointerException

Reputation: 37579

How to add a timeout to Runtime.exec() but checking exit value?

As you know, you can add a timeout to a exec() using this:

Process p = ...
if(!p.waitFor(1, TimeUnit.MINUTES)) {
    //timeout - kill the process. 
    p.destroyForcibly();
}

The problem is that using that code snippet you can't know the result value of the process, and I need to know it because i need to know if the exit value is 0 (success) or different of 0 (error).

Is there a way to achieve this?

If you use the old method, you can, but is not compatible with a timeout:

exit = process.waitFor();

Upvotes: 1

Views: 678

Answers (1)

ᴇʟᴇvᴀтᴇ
ᴇʟᴇvᴀтᴇ

Reputation: 12751

You can use p.exitValue() to get hold of the exit value, but note that you will get an IllegalThreadStateException if the subprocess represented by this Process object has not yet terminated so don't use this method if the waitFor() times out.

Process p = ...
if(!p.waitFor(1, TimeUnit.MINUTES)) {
    //timeout - kill the process. 
    p.destroyForcibly();
} else {
    int exitValue = p.exitValue();
    // ...
}

Upvotes: 3

Related Questions