如何在退出前处理程序中杀死 bash 脚本的所有后台进程和衍生进程?

发布于 2025-01-12 05:30:21 字数 831 浏览 3 评论 0原文

我正在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文