Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Clean Up Processes Launched by Runtime.exec()?

Tags:

java

windows

When my Java program is halted abnormally, applications started by Runtime.exec() do not stop. How do I stop these applications?

Process process = null;
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable()
{
     public void run() {
          process.destroy();
     }
}));

try
{
     process = Runtime.getRuntime().exec("win.exe");
     process.waitFor();
}
catch (Exception e)
{
     e.printStackTrace();
}
finally
{
    process.destroy();
}
like image 546
user3835043 Avatar asked Nov 10 '22 05:11

user3835043


1 Answers

addShutdownHook does not execute on forced shutdown of Java such as:

  • killing from Task Manager
  • killing via Eclipse Stop button
  • kill -9 on Linux.

It does execute when using

  • Ctrl+c
  • other user initiated interruptions such as Windows shutdown.
  • kill on Linux

You can test this by compiling your Java file into a class file, then running on the command line. After running on the command line, you can press Ctrl+c to observe that the shutdown hook is executed.

To test, create RunTimeTest.java as shown below, then compile using your JDK.

For example:

"c:\Program Files\Java\jdk1.7.0_40\bin"\javac RunTimeTest.java
"c:\Program Files\Java\jdk1.7.0_40\bin"\java RunTimeTest

Test code:

import java.io.IOException;
import java.util.Arrays;

public class RunTimeTest {

    public static void main(String arguments[]) {
        ProcessBuilder processBuilder = new ProcessBuilder(Arrays.asList("notepad.exe"));

        Process process = null;
        try {
            process = processBuilder.start();
            final Process processToKill = process;
            Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println("Shutdown Hook");
                    processToKill.destroy();
                }
            }));
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (process != null) {
                System.out.println("End of try");
                process.destroy();
            }
        }
    }
}

See Javadoc for Runtime

like image 124
jazeee Avatar answered Nov 14 '22 21:11

jazeee