Last active
November 11, 2025 09:31
-
-
Save pbsds/e23059af2439590e6001a1bd6e316ce0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env bash | |
| # make CTRL-C kill background jobs | |
| # https://stackoverflow.com/a/2173421 | |
| trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM INT EXIT | |
| # wait if too many background jobs | |
| wait_max_concurrent() { | |
| local n="$1" | |
| if [[ "$n" -le 0 ]]; then | |
| echo >&2 + wait | |
| wait | |
| else | |
| while [[ "$(jobs -p | wc -l)" -ge "$n" ]]; do | |
| echo >&2 + wait -n | |
| wait -n | |
| done | |
| fi | |
| } | |
| # wait for all to terminate, and avoid the "Terminated" message on normal exit | |
| cleanup(){ | |
| wait_max_concurrent 0 | |
| trap - SIGINT SIGTERM INT EXIT | |
| } | |
| # important business logic | |
| for i in 1 2 3 4 5 6 7 8 9 10; do | |
| ( | |
| echo start $i | |
| sleep 2 | |
| echo end $i | |
| ) & | |
| wait_max_concurrent 5 | |
| done | |
| # crimes | |
| cleanup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment