【问题标题】:java runtime getruntime exec timeout returns exit always NULL and always TimeoutException?java运行时getruntime exec超时返回退出总是NULL并且总是TimeoutException?
【发布时间】:2014-07-08 12:14:30
【问题描述】:

参考

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();
        }

    }



}

【问题讨论】:

    标签: java


    【解决方案1】:

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

    另一方面,NullPointerExceptions 只是由于您希望能够自行解决的琐碎编码错误。至少我期待它。

    【讨论】:

    • 这就是这里提到的stackoverflow.com/questions/808276/…
    • 你知道为什么退出值总是为空吗?
    • 不,但你知道。你有堆栈跟踪,你有它被抛出的行号,你有带有该行号的代码行,你有在该行上取消引用的变量,并且你有它的先前历史。你不需要任何人的帮助。另一方面,我们没有这些。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    相关资源
    最近更新 更多