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

查看:68
本文介绍了在 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天全站免登陆