java 为什么 Process.waitFor() 永远不会返回?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3967932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:11:26  来源:igfitidea点击:

Why does Process.waitFor() never return?

javac++process

提问by Manuel Selva

I am launching a windows process (wrote in C++ but I don't have sources) from Java code in the following way:

我正在通过以下方式从 Java 代码启动一个 Windows 进程(用 C++ 编写,但我没有源代码):

 Process p1 = Runtime.getRuntime().exec(cmdAndParams);
 p1.waitFor();

My problem is that the waitFor() method never ends. Thus I tried to launch the process in a simple shell and it ends correctly with many print in the shell (standard output I guess).

我的问题是 waitFor() 方法永远不会结束。因此,我尝试在一个简单的 shell 中启动该进程,并且它以 shell 中的许多打印正确结束(我猜是标准输出)。

Thus I decided to create and start a thread reading the standard output even if I don't need for now these outputs. This fixed the issue.

因此我决定创建并启动一个线程来读取标准输出,即使我现在不需要这些输出。这解决了这个问题。

So my question is the following one: Is this solution the "Java standard to launch and wait for external processes having outputs" or does it means there is an issue somewhere in the native process ? If such an issue exist what C++ programming "error" can be at the origin of the issue ?

所以我的问题是以下一个:这个解决方案是“启动和等待具有输出的外部进程的 Java 标准”还是意味着本机进程中的某个地方存在问题?如果存在这样的问题,问题的根源是什么 C++ 编程“错误”?

回答by dty

This is an OS thing. The child process is writing to stdout, and that's being buffered waiting for your Java process to read it. When you don't read it, the buffer eventually fills up and the child process blocks writing to stdout waiting for buffer space.

这是操作系统的事情。子进程正在写入标准输出,并且正在缓冲等待您的 Java 进程读取它。当您不读取它时,缓冲区最终会填满,并且子进程会阻止写入 stdout 以等待缓冲区空间。

You would have to processes the child process' stdout (and stderr) whichever language you were using.

无论您使用哪种语言,您都必须处理子进程的标准输出(和标准错误)。

I suggest you read this article(all 4 pages of it) and implement the recommendations there.

我建议您阅读这篇文章(共 4 页)并在那里实施建议。