Catch a linux signal in a C program | PROGRAMMING INTERVIEWS
When the signal occurs, the process has to tell the kernel what to do with it. Your process can ignore signal, catch signal or let the default action apply.
If a process wishes to handle a signal then in the code, the process has to register a signal handling function to the kernel.
How to gracefully handle the SIGKILL signal in Java - Stack Overflow
The way to handle this for anything other than
http://www.oracle.com/technetwork/java/javase/signals-139944.html
When the signal occurs, the process has to tell the kernel what to do with it. Your process can ignore signal, catch signal or let the default action apply.
Note: SIGKILL and SIGSTOP cannot be ignored.
If a process wishes to handle a signal then in the code, the process has to register a signal handling function to the kernel.
The way to handle this for anything other than
kill -9
would be to register a shutdown hook. If you can use (SIGTERM) kill -15
the shutdown hook will work. (SIGINT) kill -2
DOES cause the program to gracefully exit and run the shutdown hooks.Registers a new virtual-machine shutdown hook.
The Java virtual machine shuts down in response to two kinds of events:
when the exit (equivalently, System.exit) method is invoked, or* The program exits normally, when the last non-daemon thread exits or
interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.* The virtual machine is terminated in response to a user
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
System.out.println("Shutdown hook ran!");
}
});
I tried the following test program on OSX 10.6.3 and on
kill -9
it did NOT run the shutdown hook, didn't think it would. On a kill -15
it DOES run the shutdown hook every time.
The only real option to handle a
kill -9
is to have another watcher program watch for your main program to go away or use a wrapper script. You could do with this with a shell script that polled theps
command looking for your program in the list and act accordingly when it disappeared.