用信号陷阱中断bash中的睡眠 [英] Interrupt sleep in bash with a signal trap

查看:79
本文介绍了用信号陷阱中断bash中的睡眠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在通过sleep命令休眠的bash脚本中捕获SIGUSR1信号:

I'm trying to catch the SIGUSR1 signal in a bash script that is sleeping via the sleep command:

#!/bin/bash

trap 'echo "Caught SIGUSR1"' SIGUSR1

echo "Sleeping.  Pid=$$"
while :
do
    sleep 10
    echo "Sleep over"
done

信号陷阱起作用,但是直到sleep 10完成后,才会显示正在回显的消息.
似乎bash信号处理要等到当前命令完成后再处理信号.

The signal trap works, but the message being echoed is not displayed until the sleep 10 has finished.
It appears the bash signal handling waits until the current command finished before processing the signal.

有没有办法让它在收到信号后立即中断正在运行的sleep命令,就像C程序会中断libc sleep()函数一样?

Is there a way to have it interrupt the running sleep command as soon as it gets the signal, the same way a C program would interrupt the libc sleep() function?

推荐答案

#!/bin/bash

trap 'echo "Caught SIGUSR1"' SIGUSR1

echo "Sleeping.  Pid=$$"
while :
do
   sleep 10 &
   wait $!
   echo "Sleep over"
done

这篇关于用信号陷阱中断bash中的睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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