waitFor()方法返回null,尽管该过程已完成

时间:2015-04-16 21:31:31

标签: java

这是我的代码:

private static model connectRemoteSession(String accountName,String password) throws IOException{



            StringBuilder output = new StringBuilder();
            StringBuilder error = new StringBuilder();



            Runtime runtime = Runtime.getRuntime();


            String com = // some command

            proc = runtime.exec(com);
            Worker worker = new Worker(proc);
            reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            stderr = new BufferedReader(new InputStreamReader(
                    proc.getErrorStream()));
            String outLine;
            String errLine;
            worker.start();
            try {
                worker.join(300000);
                if (worker.exit != null){
                  //read the outout and error stream and take actions accordingly

                }

                else{
                    proc.destroy();
                    while ((outLine = reader.readLine()) != null)
                    {
                        CloudBackup.logger.info("online exchange output line    ="+outLine);
                        output.append(outLine);
                    }
                    while((errLine = stderr.readLine()) != null){
                        CloudBackup.logger.info("online exchange error line ="+errLine);
                        error.append(errLine);
                    }

                    throw new TimeoutException();
                }
            } catch(InterruptedException ex) {
                worker.interrupt();
                Thread.currentThread().interrupt();
                throw ex;
            } finally {
                proc.destroy();
            }


        }catch(Exception e){
            CloudBackup.logger.severe(e.getMessage());
        }finally{
            reader.close();
            proc.getOutputStream().close();
            stderr.close();
        }

        return model;

    }

    class Worker extends Thread {
    private final Process process;
    Integer exit;
    Worker(Process process) {
        this.process = process;
    }
    public void run() {
        try { 
            exit = process.waitFor();
        } catch (InterruptedException ignore) {
            return;
        }
    }  

我面临的这个问题是一台机器,代码工作正常,但在另一台机器上,worker.exit总是为null,虽然我把日志放在worker.exit == null中,看到这个过程正在结束但不知何故,process.waitFor没有捕获它。

我知道process.waitFor()在Java 8中可用,因此我检查了机器上的版本,并且它们具有相同版本的Java 8.此外,没有其他线程在运行。

1 个答案:

答案 0 :(得分:0)

试试这个,它可能是一个缓存问题。

 volatile Integer exit;