Examples of how to kill all child jobs when a shell script exits.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

33 lines
835 B

  1. #!/bin/sh
  2. set -e
  3. kill_child_jobs() {
  4. echo "In kill_child_jobs()..."
  5. # Workaround for https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=482999
  6. tmp="$(mktemp)"
  7. jobs -p > "$tmp"
  8. child_pids=$(cat "$tmp")
  9. for child in $child_pids
  10. do
  11. # From https://unix.stackexchange.com/a/574169
  12. if [ -n "${child##*[!0-9]*}" ]
  13. then
  14. echo Killing "$child"
  15. # From https://stackoverflow.com/a/11231970
  16. kill "$child" || true
  17. fi
  18. done
  19. # zsh version from https://stackoverflow.com/a/36354483
  20. # zsh doesn't have jobs -p
  21. jobs > "$tmp"
  22. cat "$tmp"
  23. <"$tmp" sed --regexp-extended --quiet 's/\[([[:digit:]]+)\].*running.*/%\1/gp' | while read -r child
  24. do
  25. echo Killing job "$child"
  26. kill "$child" || true
  27. done
  28. rm "$tmp"
  29. }