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.

73 lines
1.2 KiB

  1. #!/bin/sh
  2. set -e
  3. DIR="$(dirname "$0")"
  4. SCRIPT="$1"
  5. SHELL="$2"
  6. if [ ! -x "$SCRIPT" ]
  7. then
  8. >&2 echo "First argument should be file with kill_child_jobs() function to test."
  9. exit 1
  10. fi
  11. if ! command -v "$SHELL" >/dev/null
  12. then
  13. >&2 echo "Second argument should be shell to test."
  14. exit 1
  15. fi
  16. TMP="$(mktemp)"
  17. # timeout code from https://stackoverflow.com/a/10028986
  18. pidFile="$(mktemp)"
  19. (
  20. "$SHELL" "$DIR/make-and-kill-child-jobs.sh" "$SCRIPT" >"$TMP" 2>&1 || true
  21. rm "$pidFile"
  22. ) &
  23. pid=$!
  24. echo $pid > "$pidFile"
  25. (
  26. sleep 1
  27. if [ -e "$pidFile" ]
  28. then
  29. pkill -P $pid
  30. printf '∞'
  31. fi
  32. ) &
  33. killerPid=$!
  34. wait $pid
  35. kill $killerPid 2>/dev/null || true
  36. rm -f "$pidFile" || true
  37. # Make sure we've waited long enough for the "outlived" messages to be generated.
  38. sleep 0.1s
  39. if grep -q '^shell does not support disown$' "$TMP"
  40. then
  41. printf 'X'
  42. fi
  43. if ! grep -q '^disowned outlived parent.$' "$TMP"
  44. then
  45. # disowned should have outlived parent
  46. EXITCODE=2
  47. printf '☠'
  48. elif grep -q '^job outlived parent.$' "$TMP"
  49. then
  50. # job should not outlive parent
  51. EXITCODE=3
  52. printf '🏃'
  53. else
  54. # all good
  55. EXITCODE=0
  56. printf '✔️'
  57. fi
  58. rm -f "$TMP"
  59. exit $EXITCODE