在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:32:34  来源:igfitidea点击:

Catch SIGINT in bash, handle AND ignore

bash

提问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 handlerexecutes. 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 waitBEFORE program was properly shut down and created its output in its signal handler.

当我按 ctrl+c 时,将发送 SIGINT to program,但 bash 将跳过waitBEFORE 程序正确关闭并在其信号处理程序中创建其输出。

Using @suspectus answer I can change the wait $PIDto:

使用@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 INTalso will work.

所以解决方案有点笨拙,但我认为它可以满足要求。trap handler INT也将工作。

trap 'echo "Be patient"' INT

for ((n=20; n; n--))
do
    sleep 1
done