Skip to content

Instantly share code, notes, and snippets.

@Mikulas
Last active February 8, 2018 19:10
Show Gist options
  • Save Mikulas/f6ce24b55ff69f7a1715cac7aee47911 to your computer and use it in GitHub Desktop.
Save Mikulas/f6ce24b55ff69f7a1715cac7aee47911 to your computer and use it in GitHub Desktop.
Bash process control
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source /tmp/x
function handler() {
d " child: caught SIGTERM signal, exiting"
exit 0
}
trap handler SIGTERM
d " child: start $$"
for N in $(seq 1 5); do
d "child: $N"
sleep 30 &
wait $!
done
d " child: done"
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source /tmp/x
bash /tmp/sig.sh &
PID="$!"
d "master start"
sleep 1
d "master: sending SIGTERM to $PID"
kill -s TERM $PID
wait "$PID"
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source /tmp/x
child=0
function handler() {
d a" sig: caught SIGTERM signal"
d a" sig: forwarding SIGTERM to $child"
kill -s TERM "$child"
d a" sig: waiting for process $child"
wait "$child"
d a" sig: process $child exited, exiting this wrapper"
exit 0
}
trap handler SIGTERM
d a" sig: start $$"
while true; do
bash /tmp/child.sh &
child=$!
wait $child
sleep 10
done
function d() {
NOW="$(php -r 'echo microtime(TRUE);')"
echo "$NOW $@"
}
@Mikulas
Copy link
Author

Mikulas commented Feb 8, 2018

Usage:

bash run.sh

Example output:

1518116990.5304 master start
1518116990.5304   sig: start 34887
1518116990.6124     child: start 34893
1518116990.6915 child: 1
1518116991.6045 master: sending SIGTERM to 34887
1518116991.6837   sig: caught SIGTERM signal
1518116991.7661   sig: forwarding SIGTERM to 34893
1518116991.8395   sig: waiting for process 34893
1518116991.8395     child: caught SIGTERM signal, exiting
1518116991.9175   sig: process 34893 exited, exiting this wrapper

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment