问题描述
更多的概念性问题.如果我编写的bash脚本执行类似
More of a conceptual question. If I write a bash script that does something like
control_c()
{
echo goodbye
exit #$
}
trap control_c SIGINT
while true
do
sleep 10 #user wants to kill process here.
done
当睡眠10运行时,
control + c不会退出.是因为linux sleep忽略了SIGINT吗?有没有办法避免这种情况并使用户能够在睡眠状态下退出cntrl + c?
control+c won't exit when sleep 10 is running. Is it because linux sleep ignores SIGINT? Is there a way to circumvent this and have the user be able to cntrl+c out of a sleep?
推荐答案
您所描述的内容与仅发送给bash
脚本而不是进程组的中断信号是一致的.您的脚本会收到信号,但sleep
不会,因此您的陷阱要等到sleep
完成后才能执行.标准技巧是在后台运行sleep
并在其上运行wait
,以便wait
接收中断信号.然后,您还应该将SIGINT
明确发送给仍在运行的任何子进程,以确保它们退出.
What you are describing is consistent with the interrupt signal going to only your bash
script, not the process group. Your script gets the signal, but sleep
does not, so your trap cannot execute until after sleep
completes. The standard trick is to run sleep
in the background and wait
on it, so that wait
receives the interrupt signal. You should also then explicitly send SIGINT
to any child processes still running, to ensure they exit.
control_c()
{
echo goodbye
kill -SIGINT $(jobs -p)
exit #$
}
trap control_c SIGINT
while true
do
sleep 10 &
wait
done
这篇关于Linux:如何消除睡眠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!