Skip to content

Commit

Permalink
Add bg_killall
Browse files Browse the repository at this point in the history
  • Loading branch information
andsens committed Apr 19, 2024
1 parent c13273c commit 525eb5c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ Run `bg_block`, then start `...cmd` in the background and add its PID to
`$BG_PIDS`.
Does not start `...cmd` if `bg_block` fails.

#### bg_killall([SIGNAL=TERM])

Kill all running processes and wait for them to exit.
Always returns `0`.

#### bg_block([MAX=$BG_MAX_PARALLEL])

Wait until there are no more than `$MAX` running processes
Expand Down Expand Up @@ -123,6 +128,7 @@ bg_block 0
#### Run a set of watchers and exit when any of them fails

```
trap bg_killall SIGTERM SIGHUP SIGINT ERR
BG_MAXPARALLEL=-1 BG_SIGNAL=TERM
bg_run program --watch
bg_run other-program --wait
Expand Down
12 changes: 12 additions & 0 deletions bgpid.bats
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,18 @@ export -f sleep_ret
(($(date +%s) - start < 1)) || false
}

@test 'bg_killall kills all processes' {
local start
start=$(date +%s)
bash -ec "close_non_std_fds; source $BATS_TEST_DIRNAME/bgpid.sh; set -e
bg_run sleep_ret 3
bg_run sleep_ret 3
bg_run sleep_ret 3
bg_killall
"
(($(date +%s) - start < 1)) || false
}

@test 'subshell invocations do not inherit BG_PIDS' {
bash -ec "close_non_std_fds; source $BATS_TEST_DIRNAME/bgpid.sh; set -e
bg_run ret 1
Expand Down
8 changes: 8 additions & 0 deletions bgpid.sh
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ bg_run() {
"$@" & BG_PIDS+=($!)
}

bg_killall() {
[[ ${#BG_PIDS[@]} -eq 0 ]] || kill -"${1:-TERM}" "${BG_PIDS[@]}" 2>/dev/null || true
while [[ ${#BG_PIDS[@]} -gt 0 ]]; do
bg_waitany || true
done
return 0
}

# shellcheck disable=2120
bg_block() {
local lvl=$1
Expand Down

0 comments on commit 525eb5c

Please sign in to comment.