如何在使用 bash 脚本初始化的 java 应用程序中捕获信号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4147288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to trap a SIGNAL in a java application initialized using a bash script
提问by simao
I am catching an INT signal in java using the following code:
我正在使用以下代码在 java 中捕获一个 INT 信号:
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.jarto start my application I can catch the signal sent with with kill -INT PID.
当我使用java -jar file.jar来启动我的应用程序时,我可以捕获使用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.
如果我调用java -jar file.jar &(jvm 在后台运行),我无法捕捉到kill -INT.
Any ideas?
有任何想法吗?
Thanks.
谢谢。
回答by dogbane
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.
对我来说有效。您确定要杀死正确的 pid 吗?在 Unix 上,您可以使用它$!来获取您启动的最后一个进程的 pid。
$ 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.
如果您通过 shell 脚本在后台启动它,操作系统将创建一个新的进程组,该进程组不受键盘生成的信号(例如 SIGINT)的影响。只有进程组 ID 与当前终端的进程组 ID 匹配的进程才能接收这些信号。
So try running it within the current terminal's process group like this:
所以尝试在当前终端的进程组中运行它,如下所示:
. ./script.sh
You will then be able to send SIGINT.
然后,您将能够发送 SIGINT。
More information about job control here.
有关作业控制的更多信息,请点击此处。
回答by Devon_C_Miller
I going to guess the bash script is ignoring SIGINT and the child is inheriting the signal mask.
我猜 bash 脚本忽略了 SIGINT 而孩子正在继承信号掩码。
Look in the bash script for something like this. (There may be more numbers than just 2.)
在 bash 脚本中查找类似的内容。(可能有更多的数字,而不仅仅是 2。)
trap "" 2
The empty string causes the shell to set SIG_IGN. If instead you use:
空字符串会导致外壳设置 SIG_IGN。如果你使用:
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.
它注册了一个什么都不做的处理程序。当子进程启动时,任何安装了处理程序的信号都被重置为 SIG_DFL。

