繁体   English   中英

java运行时getruntime exec超时返回出口总是NULL和总是TimeoutException?

[英]java runtime getruntime exec timeout returns exit always NULL and always TimeoutException?

参考

使用Java的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();
        }

    }



}

你做错了所有。 您必须先消耗stdout和stderr上进程的所有输出, 然后才可以调用waitFor()。 否则,进程可能会阻止尝试写入自己的输出。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM