开发者

Executed program hangs (probably due too much output)

开发者 https://www.devze.com 2023-03-15 01:22 出处:网络
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:

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 trie开发者_运维技巧d to redirect the output to /dev/null, but I got a Java IOException 'Broke pipe'.


Did you try:

Process p = Runtime.getRuntime().exec("program >/dev/null 2>&1");

?

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.

class a
{
    public static void main(String[] args) throws Exception
    {
        Process p = Runtime.getRuntime().exec("cat a.java >/dev/null 2>&1");
        p.getOutputStream().write(123123);
        p.getOutputStream().flush();
        p.getOutputStream().close();
        p.waitFor();
    }
}


I'd use a Stream Gobbler. For more on that, please look here: What to do when Runtime.exec() won't


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 whose read 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号