java运行时getruntime exec timeout返回exit总是NULL并且总是TimeoutException?

时间:2014-05-20 09:45:52

标签: java

参考

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

    }



}

1 个答案:

答案 0 :(得分:3)

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

另一方面,

NullPointerExceptions只是由于你需要自己解决的琐碎编码错误。至少我期待它。