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.
|
- #!/bin/sh
- set -e
-
- DIR="$(dirname "$0")"
-
- SCRIPT="$1"
- SHELL="$2"
-
- if [ ! -x "$SCRIPT" ]
- then
- >&2 echo "First argument should be file with kill_child_jobs() function to test."
- exit 1
- fi
-
- if ! command -v "$SHELL" >/dev/null
- then
- >&2 echo "Second argument should be shell to test."
- exit 1
- fi
-
- TMP="$(mktemp)"
-
-
-
- # timeout code from https://stackoverflow.com/a/10028986
- pidFile="$(mktemp)"
- (
- "$SHELL" "$DIR/make-and-kill-child-jobs.sh" "$SCRIPT" >"$TMP" 2>&1 || true
- rm "$pidFile"
- ) &
- pid=$!
- echo $pid > "$pidFile"
- (
- sleep 1
- if [ -e "$pidFile" ]
- then
- pkill -P $pid
- printf '∞'
- fi
- ) &
- killerPid=$!
-
- wait $pid
- kill $killerPid 2>/dev/null || true
- rm -f "$pidFile" || true
-
- # Make sure we've waited long enough for the "outlived" messages to be generated.
- sleep 0.1s
-
- if grep -q '^shell does not support disown$' "$TMP"
- then
- printf 'X'
- fi
-
- if ! grep -q '^disowned outlived parent.$' "$TMP"
- then
- # disowned should have outlived parent
- EXITCODE=2
- printf '☠'
- elif grep -q '^job outlived parent.$' "$TMP"
- then
- # job should not outlive parent
- EXITCODE=3
- printf '🏃'
- else
- # all good
- EXITCODE=0
- printf '✔️'
- fi
-
- rm -f "$TMP"
- exit $EXITCODE
|