Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting a process's exit code in the case of ThreadInterrupted

I have just created a process through an exec() call and I am now using its .waitFor() method. I need to catch an InterruptedException but I am not sure what I should place in the catch code block. I would like to receive the exit code but I won't if the current thread is interrupted. What should I do to get the exit code out of the process if the thread is interrupted?

Example:

import java.io.IOException;


public class Exectest {
public static void main(String args[]){
      int exitval;

      try {
        Process p = Runtime.getRuntime().exec("ls -la ~/");
        exitval = p.waitFor();
        System.out.println(exitval);
    } catch (IOException e) {
        //Call failed, notify user.
    } catch (InterruptedException e) {
        //waitFor() didn't complete. I still want to get the exit val. 
        e.printStackTrace();
    }

}
}
like image 783
fthinker Avatar asked May 28 '11 12:05

fthinker


People also ask

How to get exit code of a process in Java?

The java. lang. Process. exitValue() method returns the exit value for the subprocess.

How do I return an exit code in Python?

You can set an exit code for a process via sys. exit() and retrieve the exit code via the exitcode attribute on the multiprocessing.

What is process finished with exit code?

What does process finished with exit code 1 mean in Python? The function calls exit(0) and exit(1) are used to reveal the status of the termination of a Python program. The call exit(0) indicates successful execution of a program whereas exit(1) indicates some issue/error occurred while executing a program.


1 Answers

If I were you, I'd put this into the catch block:

p.destroy();
exitval = p.exitValue();

Since your thread has been interrupted, something has gone wrong. destroy() will forcibly terminate the process, and then exitValue() will give you the exit value (which should be an error code since it's been terminated).

More http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html

like image 50
stevevls Avatar answered Oct 06 '22 00:10

stevevls