Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java hangs when trying to close a ProcessBuilder OutputStream

Tags:

java

process

I have the following Java code to start a ProcessBuilder, open an OutputStream, have the process write a string to an OutputStream, and then close the OutputStream. The whole thing hangs indefinitely when I try to close the OutputStream. This only happens on Windows, never on Mac or Linux.

Some of the related questions seem to be close to the same problem I'm having, but I haven't been able to figure out how to apply the answers to my problem, as I am a relative newbie with Java. Here is the code. You can see I have put in a lot of println statements to try to isolate the problem.

    System.out.println("GenMic trying to get the input file now");
    System.out.flush();
    OutputStream out = child.getOutputStream();
    try {
        System.out.println("GenMic getting ready to write the input file to out");
        System.out.flush();
        out.write(intext.getBytes());  // intext is a string previously created
        System.out.println("GenMic finished writing to out");
        System.out.flush();
        out.close();
        System.out.println("GenMic closed OutputStream");
        System.out.flush();
    } catch (IOException iox) {
        System.out.println("GenMic caught IOException 2");
        System.out.flush();
        String detailedMessage = iox.getMessage();
        System.out.println("Exception: " + detailedMessage);
        System.out.flush();
        throw new RuntimeException(iox);
    }

And here is the output when this chunk is executed:

GenMic trying to get the input file now

GenMic getting ready to write the input file to out

GenMic finished writing to out

like image 879
Jeff Bullard Avatar asked Sep 19 '25 04:09

Jeff Bullard


1 Answers

You need to make sure that the streams returned by getInputStream() and getOutputStream() are drained on individual threads and these threads are different from the one on which you close the stream returned by getOutputStream().

Basically it is a requirement to have at least 3 threads per sub-process if you want to manipulate and examine its stdin, stdout and stderr. One of the threads, depending on your circumstances, may be your current execution thread ( the one on which you create ProcessBuilder ).

like image 97
Alexander Pogrebnyak Avatar answered Sep 21 '25 20:09

Alexander Pogrebnyak