简体   繁体   English

Process.waitFor():Linux和Windows之间的区别?

[英]Process.waitFor(): Difference between Linux, and Windows?

a Java application of mine is launching an external program using Runtime.exec(String[], String[], File).我的一个 Java 应用程序正在使用 Runtime.exec(String[], String[], File) 启动一个外部程序。 In general, this is working fine.一般来说,这工作正常。 However, I notice an important difference between Linux, and Windows.但是,我注意到 Linux 和 Windows 之间的重要区别。 Suggest the following code snippet:建议以下代码片段:

Process pr = Runtime.getRuntime(cmdArray, env, workDir);
startThreadProcessingStdout(pr.getInputStream());
startThreadProcessingStderr(pr.getErrorStream());
int status = pr.waitFor();

On Windows, my threads are done when waitFor() returns.在 Windows 上,我的线程在 waitFor() 返回时完成。 (At least in the sense, that they have seen all required input.) (至少从某种意义上说,他们已经看到了所有必需的输入。)

On Linux, however, the process is gone, but the threads are still busily reading input.然而,在 Linux 上,进程消失了,但线程仍在忙于读取输入。 I can fix that by changing my snippet as follows:我可以通过如下更改我的代码段来解决这个问题:

Process pr = Runtime.getRuntime(cmdArray, env, workDir);
AtomicBoolean outRunning = startThreadProcessingStdout(pr.getInputStream());
AtomicBoolean errRunning = startThreadProcessingStderr(pr.getErrorStream());
int status = pr.waitFor();
while (outRunning  ||  errRunning) {
    Thread.sleep(100);
}

However, that seems clumsy, and slow.但是,这似乎笨拙且缓慢。 Is there a better solution for my problem?我的问题有更好的解决方案吗?

It sounds like the program you are running starts a background subprocess of its own, and this subprocess inherits the stdout and stderr file descriptors.听起来您正在运行的程序启动了它自己的后台子进程,并且该子进程继承了 stdout 和 stderr 文件描述符。

Process.waitFor waits until this the parent process exits. Process.waitFor一直等到父进程退出。 When it does, it can leave the subprocess running.当它这样做时,它可以让子进程继续运行。 Since the subprocess inherited stdout and stderr, the pipes used to communicate with Java program remain open until the subprocess exits (or closes them through other means).由于子进程继承了stdout和stderr,因此用于与Java程序通信的管道保持打开状态,直到子进程退出(或通过其他方式关闭它们)。

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

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