Java 如何处理 SIGTERM
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2975248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to handle a SIGTERM
提问by Martijn Courteaux
Is there a way in Java to handle a received SIGTERM?
Java 中有没有办法处理收到的 SIGTERM?
采纳答案by Matthew Flaschen
Yes, you can register a shutdown hook with Runtime.addShutdownHook().
是的,您可以使用Runtime.addShutdownHook().
回答by Edward Dale
You could add a shutdown hookto do any cleanup.
您可以添加关闭挂钩来进行任何清理。
Like this:
像这样:
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.
}
}
Then run it:
然后运行它:
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
回答by arcamax
Another way to handle signals in Java is via the sun.misc.signal package. Refer to http://www.ibm.com/developerworks/java/library/i-signalhandling/for understanding how to use it.
在 Java 中处理信号的另一种方法是通过 sun.misc.signal 包。请参阅http://www.ibm.com/developerworks/java/library/i-signalhandling/以了解如何使用它。
NOTE:The functionality being within sun.* package would also mean that it may not be portable/behave-the-same across all OS(s). But you may want to try it out.
注意:sun.* 包中的功能也意味着它可能无法在所有操作系统中移植/行为相同。但您可能想尝试一下。

