gpt4 book ai didi

java运行时getruntime exec超时返回退出总是NULL并且总是TimeoutException?

转载 作者:行者123 更新时间:2023-12-01 22:57:55 25 4
gpt4 key购买 nike

引用

How to add a timeout value when using Java's Runtime.exec()?

但是我总是得到worker.exit 值NULL,所以它总是抛出超时异常。下面是我的代码

public class MyClass {


private static class Worker extends Thread {
private final Process process;
private Integer exit;

private Worker(Process process) {
this.process = process;
}

public void run() {
try {
exit = process.waitFor();
} catch (InterruptedException ignore) {
return;
}
}
}


public String run(String command, long replyTimeout) throws Exception {

StringBuffer output = new StringBuffer();
Process p;
p = Runtime.getRuntime().exec(command);

BufferedReader errReader = new BufferedReader(new InputStreamReader(
p.getErrorStream()));

BufferedReader inputReader = new BufferedReader(new InputStreamReader(
p.getInputStream()));

Worker worker = new Worker(p);
worker.start();

try {
worker.join(replyTimeout);


if (worker.exit != null) {
if (worker.exit > 0) {

String line = "";
while ((line = errReader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output.toString());
System.out.println(worker.exit);
throw new Exception(output.toString());
} else {

String line = "";
while ((line = inputReader.readLine()) != null) {
output.append(line + "\n");
}
System.out.println(output.toString());
System.out.println(worker.exit);
return output.toString();
}
} else {
throw new TimeoutException();
}

} catch (InterruptedException ex) {
worker.interrupt();
Thread.currentThread().interrupt();
throw ex;
} finally {
p.destroy();
}

}



}

最佳答案

你做的这一切都是错误的。在调用 waitFor() 之前,您必须在 stdout 和 stderr 上消耗掉进程的所有输出。否则,该进程可能会阻止尝试写入自己的输出。

另一方面,NullPointerExceptions 只是由于微不足道的编码错误而导致的,您应该能够自行解决这些错误。至少我是这么期望的。

关于java运行时getruntime exec超时返回退出总是NULL并且总是TimeoutException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23756326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com