0

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;
        }
    }
1
  • Else the Java process will be ended, because the main method has been finished, along with its child processes. Commented Jan 16, 2013 at 21:40

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

isRunning() checks for Process#exitValue().

From javadoc:

Returns the exit value for the subprocess.

Returns: the exit value of the subprocess represented by this Process object. by convention, the value 0 indicates normal termination.

Throws: IllegalThreadStateException - if the subprocess represented by this Process object has not yet terminated.

Means, that IllegalThreadStateException is thrown inside isRunning() method if process is still running, but that exceptin is catched, so method return true, otherwise exitValue() return process exist value and isRunning method return false which breaks while loop.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.