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

jth*_*thg 2 java ejb

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

实际上,它只挂了一次,我无法重现它.它的生产工作近两年没有任何问题.但是,在测试应用程序的更新版本时,计时器在运行几天后就冻结了,并且从未在上次运行时释放数据库锁.日志清楚地表明它冻结在下面的代码块中的某处.它运行的命令是'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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢.

Bri*_*new 5

您需要执行标准输出/ ERR的消费同时.否则,您将获得您看到的阻止行为.有关详细信息,请参阅此答案.