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

人盡茶涼 提交于 2019-12-23 12:35:08

问题


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

}
}

回答1:


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



来源:https://stackoverflow.com/questions/6161604/extracting-a-processs-exit-code-in-the-case-of-threadinterrupted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!