问题描述
是bash中有可能拦截SIGINT,做一些事情,然后忽略它(保持的bash运行)。
Is it possible in bash to intercept a SIGINT, do something, and then ignore it (keep bash running).
我知道我可以忽略的SIGINT
I know that I can ignore the SIGINT with
trap '' SIGINT
我还可以做的东西SIGINT
And I can also do something on the sigint with
trap handler SIGINT
但是,这仍然会停止处理后的剧本
执行。例如。
#!/bin/bash
handler()
{
kill -s SIGINT $PID
}
program &
PID=$!
trap handler SIGINT
wait $PID
#do some other cleanup with results from program
当我preSS CTRL + C,在SIGINT到节目将被发送,但庆典将跳过等
程序之前,正确关闭,创造它的输出在其信号处理程序。
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.
使用@suspectus答案,我可以改变等待$ PID
来:
Using @suspectus answer I can change the wait $PID
to:
while kill -0 $PID > /dev/null 2>&1
do
wait $PID
done
这实际上对我的作品,我只是不是100%肯定,如果这是'干净'或'肮脏的解决办法。
This actually works for me I am just not 100% sure if this is 'clean' or a 'dirty workaround'.
推荐答案
陷阱从处理程序返回,但是的之后的被调用句柄时调用的命令。
trap will return from the handler, but after the command called when the handler was invoked.
因此,解决方案是一个有点笨拙,但我认为它需要什么。 陷阱处理程序INT
也可以工作。
So the solution is a little clumsy but I think it does what is required. trap handler INT
also will work.
trap 'echo "Be patient"' INT
for s in 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1
do
sleep 1
done
这篇关于捕捉SIGINT在bash,手柄和忽视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!