ProcessBuilder: process doesn't finish without "redirectOutput"

Viewed 384

I'm automating a gradle build using Java. I execute "gradlew.bat" in a Process created from a ProcessBuilder. Here's the code:

ProcessBuilder gradlewProcessBuilder = new ProcessBuilder(mainDirPath.concat("\\android\\gradlew.bat"), "assembleDebug");
gradlewProcessBuilder.directory(new File(mainDirPath.concat("/android")));
gradlewProcessBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); //This is the line
Process gradlewProcess = gradlewProcessBuilder.start();
gradlewProcess.waitFor();

Now this code works flawlessly, but it outputs the gradle console through the application console and I don't want that. If I delete this line:

gradlewProcessBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT);

The process hangs in waitFor() indefinitely.

I have absolutely no idea how could redirectOutput have effect over this, any light you can shed is welcome.

1 Answers

If the output is not redirected or handled, then a default output buffer is allocated. However, on Windows the output buffer is very small; when it fills up, the app will stop executing and will block until the output buffer is drained.

Therefore, you need to drain the output somehow; either by using INHERIT or by having a thread which drains the output. I recommend using https://github.com/zeroturnaround/zt-exec since it has much better default handling.

Related