bash Linux:如何杀死睡眠
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32041674/
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
Linux: How to kill Sleep
提问by J.Doe
More of a conceptual question. If I write a bash script that does something like
更多的是一个概念性的问题。如果我编写一个 bash 脚本,它会执行类似的操作
control_c()
{
echo goodbye
exit #$
}
trap control_c SIGINT
while true
do
sleep 10 #user wants to kill process here.
done
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?
当 sleep 10 运行时 control+c 不会退出。是不是因为 linux sleep 忽略了 SIGINT?有没有办法规避这一点,让用户能够 cntrl+c 摆脱睡眠?
回答by chepner
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.
您所描述的内容与仅发送到您的bash
脚本而不是进程组的中断信号一致。您的脚本收到信号,但sleep
没有收到,因此您的陷阱在sleep
完成之前无法执行。标准技巧是sleep
在后台运行并wait
在其上运行,以便wait
接收中断信号。然后,您还应该明确发送SIGINT
给任何仍在运行的子进程,以确保它们退出。
control_c()
{
echo goodbye
kill -SIGINT $(jobs -p)
exit #$
}
trap control_c SIGINT
while true
do
sleep 10 &
wait
done
回答by Kal
control+c won't exit when sleep 10 is running.
当 sleep 10 运行时 control+c 不会退出。
That's not true. control+c DOES exit, even if sleep is running.
这不是真的。control+c 确实退出,即使 sleep 正在运行。
Are you sure your script is executing in bash? You should explicitly add "#!/bin/bash" on the first line.
你确定你的脚本是在 bash 中执行的吗?您应该在第一行明确添加“#!/bin/bash”。
回答by Azer H
Since sleep is not bash function but external app, I guess Ctrl+C gets caught by sleep process, which normally should terminate it.
So for contorl_c function to be executed while in sleep, user must press Ctrl+C twice: 1st - to exit sleep, 2nd to get caught by bash trap.
由于 sleep 不是 bash 函数而是外部应用程序,我猜 Ctrl+C 被睡眠进程捕获,通常应该终止它。
因此,要在睡眠状态下执行 contorl_c 函数,用户必须按 Ctrl+C 两次:第一次 - 退出睡眠,第二次被 bash 陷阱捕获。