Difference between Linux, and Windows? (Linux和Windows之间的区别?)

huangapple go评论82阅读模式
英文:

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

问题

My translation of the provided text:

我的一个Java应用程序使用Runtime.exec(String[], String[], File)启动外部程序。总的来说,这个方法运行良好。然而,我注意到Linux和Windows之间存在一个重要的区别。建议以下代码片段:

在Windows上,当waitFor()返回时,我的线程已经完成了任务(至少从它们已经看到的所有所需输入来看)。

然而,在Linux上,进程已经结束,但线程仍在忙于读取输入。我可以通过更改代码片段来解决这个问题:

在Windows上,当waitFor()返回时,我的线程已经完成了任务(至少从它们已经看到的所有所需输入来看)。

然而,在Linux上,进程已经结束,但线程仍在忙于读取输入。我可以通过更改代码片段来解决这个问题:

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);
}

然而,这种方法看起来笨拙且效率较低。是否有更好的解决方案?

英文:

a Java application of mine is launching an external program using Runtime.exec(String[], String[], File). In general, this is working fine. However, I notice an important difference between Linux, and 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. (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. 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?

答案1

得分: 1

以下是翻译好的部分:

"它听起来像是您正在运行的程序启动了一个自己的后台子进程,而这个子进程继承了标准输出和标准错误文件描述符。

Process.waitFor 会等待父进程退出。当父进程退出时,它可能会保留子进程在运行。由于子进程继承了标准输出和标准错误,用于与Java程序通信的管道会保持打开状态,直到子进程退出(或通过其他方式关闭它们)。"

英文:

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.

Process.waitFor waits until this the parent process exits. 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).

huangapple
  • 本文由 发表于 2020年8月11日 19:51:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63357558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定