在ThreadInterrupted的情况下提取进程的退出代码 [英] Extracting a process's exit code in the case of ThreadInterrupted

查看:122
本文介绍了在ThreadInterrupted的情况下提取进程的退出代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚通过exec()调用创建了一个进程,现在我正在使用 其.waitFor()方法.我需要捕获一个InterruptedException,但我是 不知道我应该在catch代码块中放置什么. 我想接收退出代码,但是如果当前线程不发送 被打断了.我应该怎么做才能使退出代码退出流程 如果线程被中断了?

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?

示例:

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

}
}

推荐答案

如果我是你,我会将其放入catch块:

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

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

由于您的线程已被中断,所以出现了问题. destroy()将强制终止该过程,然后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).

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

这篇关于在ThreadInterrupted的情况下提取进程的退出代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆