执行的程序挂起(可能是由于输出太多)
我试图运行一个程序,忽略其输出,但当其输出很大时,它似乎会挂起。我的代码如下:
Process p = Runtime.getRuntime().exec("program");
p.getOutputStream().write(input.getBytes());
p.getOutputStream().flush();
p.getOutputStream().close();
p.waitFor();
忽略输出的最佳方法是什么?
我尝试将输出重定向到 /dev/null,但收到 Java IOException 'Broke pipeline'。
I'm trying to run a program ignoring its output, but it seems to hangs when its output is large. My code is as follows:
Process p = Runtime.getRuntime().exec("program");
p.getOutputStream().write(input.getBytes());
p.getOutputStream().flush();
p.getOutputStream().close();
p.waitFor();
What is the best way to ignore the output?
I tried to redirect the output to /dev/null, but I got a Java IOException 'Broke pipe'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你尝试过吗:
?
我记得以前曾在 Java 中做过类似的事情,但我可能没有以相同的方式调用该过程。
编辑:我刚刚测试了这段代码,它成功完成了。
Did you try:
?
I remember having to do something similar in Java before, but I may not have been calling the process the same way.
Edit: I just tested this code and it successfully completes.
我会使用 Stream Gobbler。有关更多信息,请查看此处:什么时候该做什么Runtime.exec() 不会
I'd use a Stream Gobbler. For more on that, please look here: What to do when Runtime.exec() won't
在 Java 中,你不能“忽略”子进程的输出,至少在技术上是这样。您应该读取输入流的内容,因为不这样做将导致另一端的输出缓冲区填满,从而导致所描述的挂起行为。当子进程尝试写入已满的输出缓冲区时,它将阻塞,直到通过读取缓冲区来清除该缓冲区。
如果您不想要输出,至少读取它并丢弃它。
或者使用 NullInputStream。您不必使用 Apache Commons 类;您可以构建自己的 NullInputStream 类,其read
方法具有空主体,类似于 NullOutputStreams.另外,仅通过读取输入流可能无法解决此问题。您还必须读取错误流,该错误流可能会重定向到输入流。
You cannot "ignore" the output of a child process in Java, well at least technically. You ought to read the contents of the input stream, for not doing so will result in the output buffer on the other end filling up, resulting in the described hanging behavior. When the child process attempts to write to a full output buffer, it will block until the buffer has been cleared by reading it.
If you do not want the output, at least read it and discard it.
Or use a NullInputStream. You do not have to use Apache Commons class; you can build your own NullInputStream class whoseread
methods have empty bodies, similar to NullOutputStreams.Also, this problem might not be solved by reading the input stream alone. You would have to read the error stream as well, which may be redirect to the input stream.