gpt4 book ai didi

java - 执行 shell 命令时永远挂起 (Java)

转载 作者:行者123 更新时间:2023-12-02 15:20:40 25 4
gpt4 key购买 nike

有问题的代码块如下。该代码几乎总是有效,但有时它会永远挂起。该应用程序是一个 EJB 计时器 bean。

实际上,它只挂起一次,我无法重现它。它在生产中运行了近 2 年,没有出现任何问题。但是,在测试应用程序的更新版本时,计时器在运行几天后就卡住了,并且从未释放上次运行时的数据库锁。日志清楚地表明它卡住在下面代码块的某个位置。它运行的命令是“chmod”。

public void shellExec(String cmd, File workDir) {
String s = null;
try {
Process p = Runtime.getRuntime().exec(cmd, null, workDir);
int i = p.waitFor();
if (i == 0){
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
// read the output from the command
while ((s = stdInput.readLine()) != null) {
logger.debug(s);
}
}
else {
BufferedReader stdErr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
// read the output from the command
while ((s = stdErr.readLine()) != null) {
logger.debug(s);
}
}
} catch (Exception e) {
logger.debug(e);
}
}

我对修改这段代码犹豫不决,因为它已经过测试并且已经正确工作了近两年。我也无法重现这个问题,所以我不知道重写的版本是否更好。但是,很明显它可能会挂起,但我不知道可能性有多大。

通过谷歌搜索该问题,该代码块似乎是执行 shell 命令的相当标准的。该代码是否存在任何已知问题?考虑到我无法重现该问题,有谁知道有什么好方法来确保它会抛出异常而不是挂起?

谢谢。

最佳答案

您需要同时执行stdout/err的消耗。否则你会看到你看到的阻塞行为。请参阅this answer了解更多信息。

关于java - 执行 shell 命令时永远挂起 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3284872/

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