在 bash 中捕获 SIGINT,处理和忽略
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15785522/
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
Catch SIGINT in bash, handle AND ignore
提问by Zulan
Is it possible in bash to intercept a SIGINT, do something, and then ignore it (keep bash running).
在 bash 中是否有可能拦截 SIGINT,做一些事情,然后忽略它(保持 bash 运行)。
I know that I can ignore the SIGINT with
我知道我可以忽略 SIGINT
trap '' SIGINT
And I can also do something on the sigint with
我也可以在 sigint 上做一些事情
trap handler SIGINT
But that will still stop the script after the handler
executes. E.g.
但这仍然会在handler
执行后停止脚本。例如
#!/bin/bash
handler()
{
kill -s SIGINT $PID
}
program &
PID=$!
trap handler SIGINT
wait $PID
#do some other cleanup with results from program
When I press ctrl+c, the SIGINT to program will be sent, but bash will skip the wait
BEFORE program was properly shut down and created its output in its signal handler.
当我按 ctrl+c 时,将发送 SIGINT to program,但 bash 将跳过wait
BEFORE 程序正确关闭并在其信号处理程序中创建其输出。
Using @suspectus answer I can change the wait $PID
to:
使用@suspectus 答案,我可以将其更改wait $PID
为:
while kill -0 $PID > /dev/null 2>&1
do
wait $PID
done
This actually works for me I am just not 100% sure if this is 'clean' or a 'dirty workaround'.
这实际上对我有用我只是不是 100% 确定这是“干净的”还是“肮脏的解决方法”。
采纳答案by suspectus
trap will return from the handler, but afterthe command called when the handler was invoked.
trap 将从处理程序返回,但在调用处理程序时调用的命令之后。
So the solution is a little clumsy but I think it does what is required. trap handler INT
also will work.
所以解决方案有点笨拙,但我认为它可以满足要求。trap handler INT
也将工作。
trap 'echo "Be patient"' INT
for ((n=20; n; n--))
do
sleep 1
done