如何向 Runtime.exec() 添加超时但检查退出值?

How to add a timeout to Runtime.exec() but checking exit value?

如您所知,您可以使用以下方法向 exec() 添加超时:

Process p = ...
if(!p.waitFor(1, TimeUnit.MINUTES)) {
    //timeout - kill the process. 
    p.destroyForcibly();
}

问题是使用该代码片段您无法知道过程的结果值,而我需要知道它,因为我需要知道退出值是 0(成功)还是不同的 0(错误)。

有办法实现吗?

如果您使用旧方法,则可以,但与超时不兼容:

exit = process.waitFor();

您可以使用 p.exitValue() 来获取退出值,但请注意,如果此 Process 对象表示的子流程尚未终止,您将获得 IllegalThreadStateException,因此不要使用此方法如果 waitFor() 超时。

Process p = ...
if(!p.waitFor(1, TimeUnit.MINUTES)) {
    //timeout - kill the process. 
    p.destroyForcibly();
} else {
    int exitValue = p.exitValue();
    // ...
}