3

I am creating a java swing application when allows the use to execute multiple commands for the command line. I have already added this line of code to ensure my swing application exits on close:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

However, how can I make sure all processes invoked by the swing application are all destroyed if I close the gui. This is my code to execute a command through the gui:

    Process p;
    String command = "java -jar blah blah blah";
    try {
        System.out.println("Export Command To Execute: " + command);
        p = Runtime.getRuntime().exec(command);
        p.waitFor();
        //BufferedReader inputStream = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader errorStream = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        String line = "";
        String output ="";
        while((line = errorStream.readLine()) != null) {
            output+=line;
        }

        //inputStream.close();
        errorStream.close();
        System.out.println(output);
        System.out.println("Export complete!...");

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

The user of the application can execute multiple commands in the application, and each command can take a while to run, so I want to make sure all the processes created by the application are killed instead of letting them run continuously if the user choose to close the application.

simhuang
  • 495
  • 3
  • 8
  • 20
  • all Java APIs required try - catch - finally block has method close(), use this method in finally – mKorbel Jan 06 '16 at 17:07
  • Put `waitFor` AFTER the processing of the `Input/Error` streams, some processes may stall if their buffers are not processed in a timely fashion. Consider using `ProcessBuilder` instead of `Process`, as you can redirect the error stream to the output stream. You should also have a look at the `destory` method – MadProgrammer Jan 06 '16 at 20:16

1 Answers1

2

See this : How to close a Java Swing application from the code and also if you have started java processes, you can kill them using command :"taskkill /pid xxx" ( assuming windows )after closing swing application. I am assuming you can get pids of processes you have started inside swign application commands. How do I find the process ID (pid) of a process started in java?

Community
  • 1
  • 1
SomeDude
  • 13,876
  • 5
  • 21
  • 44