如何在退出前处理程序中杀死 bash 脚本的所有后台进程和衍生进程?
我正在使用 wait -n
技术来执行 max_jobs
并行任务:
#!/usr/bin/env bash
cleanup() {
echo "cleaning up..."
}
trap "cleanup" EXIT
do_task() {
echo "doing task" "$1" " ..."
sleep 3s
}
main_task() {
for ((j = 0; j < 10; j++)); do
((i++ < max_jobs)) || wait -n
do_task "$j" &
done
wait
}
i=0
max_jobs=4
main_task
如何终止此脚本生成的所有作业和进程(在 cleanup
中) > 处理程序)如果我按 Ctrl+C
?
我尝试在 cleanup
中执行 kill 0
,但它似乎并没有杀死悬空的 do_task
作业。
请注意,如果我在前 3 秒内发送 SIGTERM
(Ctrl+C
),它会终止脚本。但如果我等到 5 秒然后发送 SIGTERM
,突然一个悬空进程消耗了 100% 的 CPU,就好像它陷入了无限循环。我必须在 htop
中关注该进程,并手动向其发送 SIGKILL
。
I'm using the wait -n
technique to perform max_jobs
parallel tasks:
#!/usr/bin/env bash
cleanup() {
echo "cleaning up..."
}
trap "cleanup" EXIT
do_task() {
echo "doing task" "$1" " ..."
sleep 3s
}
main_task() {
for ((j = 0; j < 10; j++)); do
((i++ < max_jobs)) || wait -n
do_task "$j" &
done
wait
}
i=0
max_jobs=4
main_task
How can I kill all jobs and processes spawned by this script (in cleanup
handler) if I hit Ctrl+C
?
I tried kill 0
in cleanup
, but it doesn't seem to kill the dangling do_task
jobs.
Note that if I send SIGTERM
(Ctrl+C
) in first 3 seconds, it kills the script. But if I wait until 5s and then send SIGTERM
, suddenly one dangling process consumes 100% of the CPU as if it is stuck in an infinite loop. I have to eyeball that process in htop
and send SIGKILL
to it manually.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论