Alexandru
Alexandru

Reputation: 25800

Executed program hangs (probably due too much output)

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

Upvotes: 1

Views: 1777

Answers (3)

Zéychin
Zéychin

Reputation: 4205

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();
    }
}

Upvotes: 1

Vineet Reynolds
Vineet Reynolds

Reputation: 76709

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.

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

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

Upvotes: 0

Related Questions