Big Puncho
Big Puncho

Reputation: 301

Kill both processes at the same time

I have an assignment where I must create two instances of a process and the other process must terminate when one of them is terminated. I can only do this when I close the first process created, does this means that created processes have some kind of hierarchy, even though they are both children of the same process?

Thanks in advance.

ProcessBuilder pb = new ProcessBuilder(args);
Process proc_1 = pb.start();
Process proc_2 = pb.start();
System.out.println("Child is running...wait for child to terminate");

int exitValue_1 = proc_1.waitFor();
System.out.println("Child_1 finished with exit value -> " + exitValue_1);
if(exitValue_1==0) proc_2.destroy();

int exitValue_2 = proc_2.waitFor();
System.out.println("Child_1 finished with exit value -> " + exitValue_2);
if(exitValue_2==0) proc_1.destroy();

Upvotes: 0

Views: 197

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347244

Process#exitValue will throw a IllegalThreadStateException if the process has not yet exited, you could exploit this.

ProcessBuilder pb = new ProcessBuilder(args);
Process proc_1 = pb.start();
Process proc_2 = pb.start();

boolean running = true;
while (running) {
    try {
        int exitValue = proc_1.exitValue();
        System.out.println("Child_1 finished with exit value -> " + exitValue);
        if(exitValue==0) {
            proc_2.destroy();
            running = false;
            break;
        }
    } catch (IllegalThreadStateException exp) {
    }
    try {
        int exitValue = proc_2.exitValue();
        System.out.println("Child_2 finished with exit value -> " + exitValue);
        if(exitValue==0) { 
            proc_1.destroy();
            running = false; 
            break;
        }
    } catch (IllegalThreadStateException exp) {
    }
}

Upvotes: 2

Guido Simone
Guido Simone

Reputation: 7952

does this means that created processes have some kind of hierarchy,

No. It's just the way you wrote your code. You are blocking until the first process exits and unfortunately if the second process exits first your code has no way of knowing this.

Since Java is not providing you with a "waitForEitherProcess" method, I think you will need to do a polling loop checking the status of the process. Periodically invoke exitValue on each process then sleep for a few milliseconds. If exitValue returns an int, the process has terminated. If it throws an exception it has not. Use this to decide which process has exited and which needs to be killed.

Upvotes: 3

Related Questions