Friday, July 22, 2022

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

Issue

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();

Solution

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();
    // ...
}


Answered By - ᴇʟᴇvᴀтᴇ
Answer Checked By - Mary Flores (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.