Comment manipuler un SIGTERM

Y at-il un moyen en Java de gérer un SIGTERM reçu?

Oui, vous pouvez enregistrer un hook d’arrêt avec Runtime.addShutdownHook() .

Vous pouvez append un hook d’arrêt pour effectuer un nettoyage.

Comme ça:

 public class myjava{ public static void main(Ssortingng[] 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 sortingggered, doing final cleanup. } } 

Puis lancez-le:

 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 

Une autre façon de gérer les signaux en Java consiste à utiliser le package sun.misc.signal. Référez-vous à http://www.ibm.com/developerworks/java/library/i-signalhandling/ pour comprendre comment l’utiliser.

REMARQUE: La fonctionnalité figurant dans le package sun. * Signifie également qu’elle ne peut pas être portable / se comporter de la même manière sur tous les systèmes d’exploitation. Mais vous voudrez peut-être l’essayer.