当我的Java程序异常停止时,Runtime.exec()启动的应用程序不会停止。如何停止这些应用程序?
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();
}
答案 0 :(得分:0)
最糟糕的情况:如果您多次使用该程序,则在下一次运行中您可以终止该进程。
String command = "cmd /c taskkill /f /im win.exe";
Runtime.getRuntime().exec(command);
答案 1 :(得分:0)
addShutdownHook不会在强制关闭Java时执行,例如:
使用
时执行您可以通过将Java文件编译为类文件,然后在命令行上运行来测试它。在命令行上运行后,您可以按Ctrl + c来观察执行关闭挂钩。
要测试,请创建RunTimeTest.java,如下所示,然后使用JDK进行编译。
例如:
"c:\Program Files\Java\jdk1.7.0_40\bin"\javac RunTimeTest.java
"c:\Program Files\Java\jdk1.7.0_40\bin"\java RunTimeTest
测试代码:
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();
}
}
}
}