Sample Header Ad - 728x90

How to kill all background and spawned processes of a bash script in its pre-exit handler?

1 vote
1 answer
334 views
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.
Asked by Zeta.Investigator (1190 rep)
Mar 4, 2022, 02:59 PM
Last activity: Mar 7, 2022, 12:11 PM