Java中有没有办法处理收到的SIGTERM?
问问题
49741 次
3 回答
78
是的,您可以使用Runtime.addShutdownHook()
.
于 2010-06-04T14:56:16.320 回答
57
您可以添加一个关闭挂钩来进行任何清理。
像这样:
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
于 2010-06-04T14:56:31.903 回答
4
在 Java 中处理信号的另一种方法是通过 sun.misc.signal 包。请参阅http://www.ibm.com/developerworks/java/library/i-signalhandling/了解如何使用它。
注意: sun.* 包中的功能也意味着它可能无法在所有操作系统中移植/行为相同。但是您可能想尝试一下。
于 2010-06-07T06:15:32.947 回答