PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

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

 July 22, 2022     exec, java, process, runtime, timeout     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home
View mobile version

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing