如何处理SIGTERM

Java中有处理收到的SIGTERM的方法吗?

是的,您可以使用Runtime.addShutdownHook()注册一个closures钩子。

你可以添加一个closures钩子来做任何清理。

喜欢这个:

 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。*软件包中的function也意味着它可能在所有操作系统中都不是可移植的/行为相同的。 但是你可能想尝试一下。