为什么 Process.waitFor() 永远不会返回? [英] Why does Process.waitFor() never return?

查看:64
本文介绍了为什么 Process.waitFor() 永远不会返回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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).

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

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.

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

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 进程读取它.当您不读取它时,缓冲区最终会填满,并且子进程会阻止写入 stdout 以等待缓冲区空间.

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.

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

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

我建议你阅读这篇文章(全部 4 页)并在那里实施建议.

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

这篇关于为什么 Process.waitFor() 永远不会返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆