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();
}
addShutdownHook does not execute on forced shutdown of Java such as:
It does execute when using
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With