I am catching an INT signal in java using the following code:
Signal.handle(new Signal("INT"), new SignalHandler () {
public void handle(Signal sig) {
log.warn("Received SIGINT signal. Will teardown.");
task.tearDown();
// Force exit anyway
System.exit(1);
}
});
When I am using java -jar file.jar
to start my application I can catch the signal sent with with kill -INT PID
.
If I call java -jar file.jar &
(jvm runs in the background), I can't catch the signal sent with kill -INT
.
Any ideas?
Thanks.
The trap command lets you to regulate how a program responds to a signal. A signal is an asynchronous communication consisting of a number that can be delivered from one process to another or from the operating system to a process if particular keys are pushed or if anything unusual occurs.
The syntax for the trap command is "trap COMMAND SIGNALS...", so unless the command you want to execute is a single word, the "command" part should be quoted. Note that if you send a kill -9 to your script, it will not execute the EXIT trap before exiting.
Works for me. Are you sure you are killing the right pid? On Unix you can use $!
to get the pid of the last process you launched.
$ java -jar file.jar &
[1] 25573
$ kill -INT $!
Received SIGINT signal. Will teardown.
Update:
If you are launching this in the background via a shell script, the OS will create a new process group which will be immune to keyboard-generated signals such as SIGINT. Only processes whose process group ID matches the current terminal's process group ID can receive these signals.
So try running it within the current terminal's process group like this:
. ./script.sh
You will then be able to send SIGINT.
More information about job control here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With