与 waitFor(timeout, unit) 方法一起使用时,进程不会在执行完成后立即退出

我想使用 java 执行一些 cmd 命令,所以我使用 ProcessBuilder。下面是我的示例代码。我在 Windows 10 pro build 19042 上运行此代码并使用 oracle java jdk1.8.0_191

public class ProcessBuilderEx {

  public static void main(String[] args) throws Exception {
    long start = System.currentTimeMillis();
    String[] command = new String[]{"python","-c","\"help('modules')\""};
    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command(command);

    Process process = processBuilder.start();
    InputStream inputStream = process.getInputStream();
    process.waitFor(20,TimeUnit.SECONDS);
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    Stream<String> lines = bufferedReader.lines();
    lines.forEach(System.out::println);

    long end = System.currentTimeMillis();
    System.out.println((end - start) / 1000);
  }

}

当没有使用waitFor()方法时,进程一得到结果就退出,程序终止。但是,当使用 waitFor(long timeout,TimeUnit unit) 方法时,进程在获得结果时不会退出,而是等待给定的超时时间并获得结果然后退出。

以下是方法文档

Causes the current thread to wait,if necessary,until the subprocess represented by this Process object has terminated,or the specified waiting time elapses.
If the subprocess has already terminated then this method returns immediately with the value true. If the process has not terminated and the timeout value is less than,or equal to,zero,then this method returns immediately with the value false.
The default implementation of this methods polls the exitvalue to check if the process has terminated. Concrete implementations of this class are strongly encouraged to override this method with a more efficient implementation.
Params:
timeout – the maximum time to wait
unit – the time unit of the timeout argument
Returns:
true if the subprocess has exited and false if the waiting time elapsed before the subprocess has exited.
Throws:
InterruptedException – if the current thread is interrupted while waiting.
NullPointerException – if unit is null
Since:
1.8
public boolean waitFor(long timeout,TimeUnit unit)
        throws InterruptedException...

根据方法#waitFor(long timeout,TimeUnit unit) 的文档中所述,它应该在获得结果后立即返回结果,但它等待整个 20 秒超时然后终止。我不明白这种行为。是错误还是我遗漏了什么。

wpcwpcwpcwpc 回答:与 waitFor(timeout, unit) 方法一起使用时,进程不会在执行完成后立即退出

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/28472.html

大家都在问