Search code examples
javawindowsmavencmdprocessbuilder

Maven exec with ProcessBuilder stops processing


I am running my code as;

mvn exec:java@xxxxxxxxxxxx -Dexec.args="hello"

I don't know why but somehow it stops processing. It is getting stuck after 10 or 20 seconds. But this is happening with the ProcessBuilder;

Here is how I run it:

public static long runCommandLine(String commandLineArgs){
        try {
            ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/c", commandLineArgs);
            Process process = pb.start();
            if(!commandLineArgs.contains("runner")) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                while ((reader.readLine()) != null) { /*haha*/}
                process.waitFor();
            }
            return process.pid();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

I send the .bat file's path to the method as an argument (String commandLineArgs);

.bat file contains lines:

cd C:/xxxx/%username%/xxx
mvn exec:java@xxxxxxxxxxxx -Dexec.args="hello"

If I run the .bat file manually, everything is okay. But with the ProcessBuilder it will get stuck after a while.

pom.xml configutarion:

<plugin>
                    <groupId>org.codehaus.mojo</groupId>
                    <artifactId>exec-maven-plugin</artifactId>
                    <version>1.6.0</version>
                    <executions>
                        <execution>
                            <id>xxxxxxxx</id>
                            <configuration>
                                <mainClass>xxxxxxxxxxx</mainClass>
                            </configuration>
                        </execution>
                   </executions>
</plugin>

Solution

  • as khmarbaise mentioned "ProcessBuilder.redirectError and ProcessBuilder.redirectOutput should be used and afterwards you can read from it...", the solution is adding redirects.