Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle signals in the Java Virtual Machine

Is it possible to handle POSIX signals within the Java Virtual Machine?

At least SIGINT and SIGKILL should be quite platform independent.

like image 561
Benedikt Waldvogel Avatar asked Sep 02 '08 19:09

Benedikt Waldvogel


People also ask

How are signals handled?

A signal is a software interrupt delivered to a process. The operating system uses signals to report exceptional situations to an executing program. Some signals report errors such as references to invalid memory addresses; others report asynchronous events, such as disconnection of a phone line.

What is Libjsig so?

The libjsig.so is the answer for this problem: it replaces the system signal APIs (sigaction() etc) with its own versions, and any user code attempting to install a signal handler will not replace the global signal handler but the user handler will be chained behind the (already installed) Java VM signal handler.


2 Answers

The JVM responds to signals on its own. Some will cause the JVM to shutdown gracefully, which includes running shutdown hooks. Other signals will cause the JVM to abort without running shutdown hooks.

Shutdown hooks are added using Runtime.addShutdownHook(Thread).

I don't think the JDK provides an official way to handle signals within your Java application. However, I did find this IBM article, which describes using some undocumented sun.misc.Signal class to do exactly that. The article dates from 2002 and uses JDK 1.3.1, but I've confirmed that the sun.misc.Signal class still exists in JDK 1.6.0.

like image 57
Will Avatar answered Sep 29 '22 01:09

Will


Perhaps Runtime#addShutdownHook ?

like image 26
toolkit Avatar answered Sep 29 '22 01:09

toolkit