Ujjwal Prakash
Ujjwal Prakash

Reputation: 137

how to get to know if a process invoked with process builder/ Runtime in Java has completed its execution or not

In Java i am firing a command on the shell using Process builder and after firing that command i want to know its progress whether its complete or not. If the process invoked is taking too much time i want to kill that process after a certain time limit. e.g if the process is taking more than 5 sec to execute i want to kill that back end process and if its complete within 5 sec i want to continue using the output of that back end process. In python there is class variable called returncode which is initially null and then gets to 0 after the process has completed it execution and i can keep on checking that value and if its null after 5 sec i can simply kill that process. How can i do the same thing in Java ?

Upvotes: 3

Views: 2315

Answers (1)

Tomek Rękawek
Tomek Rękawek

Reputation: 9304

Method Process#exitValue() throws an exception if the process has not yet terminated.

You can start the process, sleep for 5 seconds and invoke exitValue(). If you get IllegalThreadStateException it means the process is still running and you can kill it with destroy() method:

Process p = ...
try {
    Thread.sleep(5 * 1000);
    int exitValue = p.exitValue();
    // get the process results here
} catch (IllegalThreadStateException e) {
    // process hasn't terminated in 5 sec
    p.destroy();
}

Upvotes: 2

Related Questions