【发布时间】:2011-02-27 20:22:53
【问题描述】:
Java 中有没有办法处理收到的 SIGTERM?
【问题讨论】:
Java 中有没有办法处理收到的 SIGTERM?
【问题讨论】:
是的,您可以使用Runtime.addShutdownHook() 注册关闭挂钩。
【讨论】:
System.exit(1) 在其他地方执行时,该钩子是否也会被触发?我正在尝试遵循这种模式来处理我的多线程 Java 程序的受控停止,我发现 System.exit(1) 没有终止 JVM。
您可以添加shutdown hook 进行任何清理。
像这样:
public class myjava{
public static void main(String[] args){
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Inside Add Shutdown Hook");
}
});
System.out.println("Shut Down Hook Attached.");
System.out.println(5/0); //Operating system sends SIGFPE to the JVM
//the JVM catches it and constructs a
//ArithmeticException class, and since you
//don't catch this with a try/catch, dumps
//it to screen and terminates. The shutdown
//hook is triggered, doing final cleanup.
}
}
然后运行它:
el@apollo:~$ javac myjava.java
el@apollo:~$ java myjava
Shut Down Hook Attached.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at myjava.main(myjava.java:11)
Inside Add Shutdown Hook
【讨论】:
在 Java 中处理信号的另一种方法是通过 sun.misc.signal 包。使用方法请参考http://www.ibm.com/developerworks/java/library/i-signalhandling/。
注意: sun.* 包中的功能也意味着它可能无法在所有操作系统中移植/行为相同。但您可能想尝试一下。
【讨论】: