问题
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.
回答1:
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.
回答2:
I going to guess the bash script is ignoring SIGINT and the child is inheriting the signal mask.
Look in the bash script for something like this. (There may be more numbers than just 2.)
trap "" 2
The empty string causes the shell to set SIG_IGN. If instead you use:
trap ":" 2
That registers a handler that does nothing. When a child process is started, any signal with a handler installed is reset to SIG_DFL.
来源:https://stackoverflow.com/questions/4147288/how-to-trap-a-signal-in-a-java-application-initialized-using-a-bash-script