Jtaylorapps
Jtaylorapps

Reputation: 5770

Kill a process created in a different class

Say I run a program in my Process class, something like:

Process p1 = Runtime.getRuntime().exec("setup.exe");
try {
    p1.waitFor();
} catch (InterruptedException e) {
    //Whatever
}

And then I also have a cancel button in my GUI class, something along the lines of:

private void cancelButtonActionPerformed(ActionEvent e) {
    //Need to interrupt the thread from here!
    System.exit(0);
}

Simply exiting the program out as is leaves my setup.exe process I created over in Process.java running, and that's a problem. Normally I'd call p1.destroy(), but I'm having issues making the connection in between the two classes.

Any suggestions would be much appreciated!

EDIT:

private void beginThread() {
        SwingWorker<String, Void>  myWorker = new SwingWorker<String, Void>() {
            @Override
            protected String doInBackground() throws Exception {
                //Do some stuff
            }
        return null;
        }
    };
    myWorker.execute();
}

Upvotes: 1

Views: 85

Answers (1)

assylias
assylias

Reputation: 328608

Assuming your run the process in a separate thread, you can call processThread.interrupt() from your GUI class.

You then simply need to modify the try/catch to:

try {
    p1.waitFor();
} catch (InterruptedException e) {
    Sys.err(e.toString());
    //don't ignore the exception:
    p1.destroy();
    Thread.currentThread.interrupt(); //reset interrupted flag
}

Upvotes: 2

Related Questions