簡體   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