为什么我的bash脚本这么长的时间作出回应时,它在后台运行杀? [英] Why does my bash script take so long to respond to kill when it runs in the background?

查看:221
本文介绍了为什么我的bash脚本这么长的时间作出回应时,它在后台运行杀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(修订问题,现在我更多地了解什么是实际发生的事情)的:

我有在后台运行的脚本,定期做一些工作,然后睡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 or kill 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 via kill or kill -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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆