Java Process.waitFor()和Readline挂起

Hug*_*ugo 3 java powershell vmware multithreading

首先,这是我的代码:

import java.io.*;
import java.util.Date;

import com.banctecmtl.ca.vlp.shared.exceptions.*;

public class PowershellTest implements Runnable {

public static final String PATH_TO_SCRIPT = "C:\\Scripts\\ScriptTest.ps1";
public static final String SERVER_IP = "XX.XX.XX.XXX";
public static final String MACHINE_TO_MOD = "MachineTest";

/**
 * @param args
 * @throws OperationException 
 */
public static void main(String[] args) throws OperationException {

    new PowershellTest().run();

}

public PowershellTest(){}

@Override
public synchronized void run() {
    String input = "";
    String error = "";

    boolean isHanging = false;

    try {

        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec("powershell -file " + PATH_TO_SCRIPT +" "+ SERVER_IP +" "+ MACHINE_TO_MOD);
        proc.getOutputStream().close();
        InputStream inputstream = proc.getInputStream();
        InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

        proc.waitFor();

        String line;
        while (!isHanging && (line = bufferedreader.readLine()) != null) {
            input += (line + "\n");
            Date date = new Date();
            while(!bufferedreader.ready()){

                this.wait(1000);
                //if its been more then 1 minute since a line has been read, its hanging. 
                if(new Date().getTime() - date.getTime() >= 60000){

                    isHanging = true;
                    break;

                }
            }
        }

        inputstream.close();
        inputstream = proc.getErrorStream();
        inputstreamreader = new InputStreamReader(inputstream);
        bufferedreader = new BufferedReader(inputstreamreader);
        isHanging = false;

        while (!isHanging && (line = bufferedreader.readLine()) != null) {
            error += (line + "\n");
            Date date = new Date();
            while(!bufferedreader.ready()){

                this.wait(1000);
                //if its been more then 1 minute since a line has been read, its hanging. 
                if(new Date().getTime() - date.getTime() >= 60000){

                    isHanging = true;
                    break;

                }
            }
        }
        inputstream.close();

        proc.destroy();

    } catch (IOException e) {
        //throw new OperationException("File IO problem.", e);
    } catch (InterruptedException e) {
        //throw new OperationException("Script thread problem.",e);
    }
    System.out.println("Error : " + error + "\nInput : " + input);
}
Run Code Online (Sandbox Code Playgroud)

}

我目前正在尝试运行Powershell脚本,该脚本将在远程服务器上启动/停止VM(VMWARE)。该脚本从命令行运行,此代码也是如此。问题是,我讨厌这样的工作必须使用线程(让线程等待脚本响应,如进一步说明)。我必须这样做,因为BufferedReader.readline()和proc.waitFor()都永远挂起。

从cmd运行时,该脚本执行时间很长。从与服务器验证身份并执行实际脚本起,它会停顿30秒到1分钟。从调试中可以看到,当读取行开始从脚本中接收到这些延迟时,readline将挂起。

我也很确定这不是内存问题,因为在任何调试会话中都没有任何OOM错误。

现在,我了解到Process.waitFor()要求我从错误流和常规流中清除缓冲区才能正常工作,所以这就是为什么我不使用它的原因(我需要输出来管理特定于VM的错误,证书问题等)。

我想知道是否有人可以向我解释它为什么挂起,以及是否有一种方法可以仅使用典型的readline()而不使它挂得太难。即使脚本应该已经结束了一段时间,它仍然会挂起(我尝试同时使用我在Java应用程序中使用的完全相同的东西运行Java应用程序和cmd命令,将其运行1h,没有任何效果)。它不仅停留 while循环中,而且readline()是挂起的地方。

这也是一个测试版本,距离最终代码还很遥远,所以请避免我:这应该是一个常量,这是没有用的,等等。我稍后将清理代码。显然,我的代码中的IP不是XX.XX.XX.XXX。

无论如何解释或建议都将不胜感激。

呵呵,这是我当前使用的脚本:

Add-PSSnapin vmware.vimautomation.core

Connect-VIServer -server $args[0]

Start-VM -VM "MachineTest"
Run Code Online (Sandbox Code Playgroud)

如果您需要更多详细信息,我会尽力提供。

在此先感谢您的帮助!

编辑:我以前也用要求不高的脚本测试了代码,该工作是获取文件的内容并打印出来。由于无需等待即可获取信息,因此readline()效果很好。因此,我非常确定问题出在脚本执行的等待时间上。

另外,请原谅我的错误,英语不是我的主要语言。

在此先感谢您的帮助!

EDIT2:由于我无法回答自己的问题:

这是使用线程后的“最终”代码:

import java.io.*;

public class PowershellTest implements Runnable {

public InputStream is;

public PowershellTest(InputStream newIs){

    this.is = newIs;
}

@Override
public synchronized void run() {
    String input = "";
    String error = "";

    try {


        InputStreamReader inputstreamreader = new InputStreamReader(is);
        BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

        String line;
        while ((line = bufferedreader.readLine()) != null) {
            input += (line + "\n");

        }

        is.close();

    } catch (IOException e) {
        //throw new OperationException("File IO problem.", e);
    }
    System.out.println("Error : " + error + "\nInput : " + input);
}

}
Run Code Online (Sandbox Code Playgroud)

而主线程只需创建并启动2个线程(PowerShellTest实例),其中1个线程带errorStream,1个线程带inputStream。

我相信我在第一次编写应用程序代码时就犯了一个愚蠢的错误,并在反复修改代码时以某种方式修复了该错误。它仍然需要5-6分钟才能运行,如果不超过我之前的代码,这在某种程度上是相似的(这是合乎逻辑的,因为在我的情况下errorStream和inputStream会顺序获取它们的信息)。

无论如何,感谢您的所有回答,尤其是Miserable Variable对线程的提示。

Ian*_*rts 5

首先,waitFor()在您完成阅读流之后才打电话。我强烈建议您查看ProcessBuilder而不是简单地使用Runtime.exec,并自己拆分命令,而不要依赖Java来为您做这件事:

ProcessBuilder pb = new ProcessBuilder("powershell", "-file", PATH_TO_SCRIPT,
        SERVER_IP, MACHINE_TO_MOD);
pb.redirectErrorStream(true); // merge stdout and stderr
Process proc = pb.start();
Run Code Online (Sandbox Code Playgroud)

redirectErrorStream将错误输出合并到正常输出,因此您只需阅读即可proc.getInputStream()。然后,您应该可以只读取该流,直到EOF,然后调用proc.waitFor()