英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论