Search code examples
javaprocessbatch-fileprocessbuilder

Strange issue while running batch file with process builder in java


I have the following java code snippet which runs a batch file( renames a file depending on a flag ). This code works properly. But when i comment the line while( isRunning(p) ) {} then it doesn't work. Can anyone give any reason for that ?

public static void main(String[] args) throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder(  fileManipulatorScriptLocation, "Rename_File", "a.txt", "b.txt" );
        pb.directory( new File(targetDirectory) );
        Process p = pb.start();
        while( isRunning(p) ) {}
    }

    public static boolean isRunning(Process process) {
        try {
            process.exitValue();
            return false;
        } catch (IllegalThreadStateException e) {
            return true;
        }
    }

Solution

  • Instead of the busy-waiting infinite loop, use Process#waitFor. Why it doesn't work: your parent process (Java) dies immediately, dragging the child process with it.