为什么我的bash脚本这么长的时间作出回应时,它在后台运行杀? [英] Why does my bash script take so long to respond to kill when it runs in the background?
问题描述
的(修订问题,现在我更多地了解什么是实际发生的事情)的:
我有在后台运行的脚本,定期做一些工作,然后睡30秒:
回声后台脚本PID:$$
陷阱回声退出...'INT退出
而真实的;做
#检查的东西做什么,
睡眠30
完成&功放;
如果我试着通过来杀死这个脚本杀
或杀INT
,它需要30秒的响应信号。
我将在下面回答这个问题,因为我找到了一个很好的解释网上。
(我的原创,令人尴尬的未研究的问题的)
这个问题是一个bash脚本,包括以下陷阱:
陷阱回声退出......>&放大器; 2;杀$ childPID 2 - ;的/ dev / null的;退出0'\\
SIGALRM SIGHUP SIGINT SIGKILL SIGPIPE SIGPROF SIGTERM \\
SIGUSR1 SIGUSR2 SIGVTALRM SIGSTKFLT如果我在前台运行的脚本,然后打
<大骨节病> CTRL 骨节病> - <大骨节病> C 骨节病>,它会立即得到信号并退出
(下1秒)。
如果我在后台运行相同的脚本(
&安培;
),并通过杀死它
杀
或杀-INT
,它获得信号之前需要30秒。
这是为什么,我怎么能解决这个问题?
块引用>解决方案可能的原因:过程正在睡觉发出的信号不传递,直到该进程的唤醒。当通过命令行启动,过程中不睡觉,所以信号被立即发送。
(Question revised, now that I understand more about what's actually happening):
I have a script that runs in the background, periodically doing some work and then sleeping for 30 seconds:
echo "background script PID: $$" trap 'echo "Exiting..."' INT EXIT while true; do # check for stuff to do, do it sleep 30 done &
If I try to kill this script via
kill
orkill INT
, it takes 30 seconds to respond to the signal.I will answer this question below, since I found a good explanation online.
(My original, embarrassingly un-researched question)
This question is for a bash script that includes the following trap:
trap 'echo "Exiting...">&2; kill $childPID 2>/dev/null; exit 0' \ SIGALRM SIGHUP SIGINT SIGKILL SIGPIPE SIGPROF SIGTERM \ SIGUSR1 SIGUSR2 SIGVTALRM SIGSTKFLT
If I run the script in the foreground, and hit CTRL-C, it gets the signal immediately and exits (under one sec).
If I run the same script in the background (
&
), and kill it viakill
orkill -INT
, it takes 30 seconds before getting the signal.Why is that, and how can I fix it?
解决方案Possible reason: signals issued while a process is sleeping are not delivered until wake-up of the process. When started via the command line, the process doesn't sleep, so the signal gets delivered immediately.
这篇关于为什么我的bash脚本这么长的时间作出回应时,它在后台运行杀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!