Last active
August 29, 2015 14:27
-
-
Save gustafsson/20b4619366184c58f330 to your computer and use it in GitHub Desktop.
This file contains 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 sh | |
# ./mydeamon.sh TIMEOUT CHILDAPP | |
# | |
# Creates a watchdog file WATCHDOG and executes CHILDAPP WATCHDOG. | |
# If CHILDAPP exits it is restarted. | |
# If CHILDAPP does not touch WATCHDOG within TIMEOUT seconds it is killed and restarted. | |
# This script stops CHILDAPP when it is aborted (Ctrl-C or SIGTERM). | |
set -e # abort this script if anything fails | |
SECONDS_UNTIL_KILL=$1 | |
MYAPP=$2 | |
if [ -z "$MYAPP" ] || [ -z "$SECONDS_UNTIL_KILL" ]; then | |
echo "syntax: $0 timeout childapp" | |
false | |
fi | |
WATCHDOG=`mktemp /tmp/mydeamon.XXXXXX` | |
REFFILE=`mktemp /tmp/mydeamon.XXXXXX` | |
# cleanup when this script finished | |
trap 'kill $MYAPP_PID; rm -f $WATCHDOG $REFFILE' EXIT | |
# loop to restart when dead | |
while true; do | |
echo "$0: restarting $MYAPP $WATCHDOG" | |
$MYAPP $WATCHDOG & | |
MYAPP_PID=$! | |
# loop to check age of $WATCHDOG, kill -0 dosn't kill, it just checks. | |
while `kill -0 $MYAPP_PID`; do | |
touch $REFFILE | |
sleep $SECONDS_UNTIL_KILL | |
if [ "$REFFILE" -nt "$WATCHDOG" ]; then | |
echo "$0: $MYAPP didn't touch the watchdog. Sending SIGTERM." | |
if ! kill "$MYAPP_PID"; then | |
echo "$0: $MYAPP didn't respond to SIGTERM. Sending SIGKILL." | |
kill -9 $MYAPP_PID | |
fi | |
break | |
#else | |
# echo "$0: $MYAPP touched $WATCHDOG $LASTMOD seconds ago." | |
fi | |
done | |
done |
This file contains 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 | |
# A script used to test mydeamon.sh. | |
# | |
# Run: ./mydeamon.sh 5 ./mydeamontest.sh | |
# This script should be restarted. | |
# | |
# Run: ./mydeamon.sh 15 ./mydeamontest.sh | |
# This script should never be restarted and print a fail message. | |
# | |
# No dangling resources should be left when mydeamon.sh is aborted. These commans should be empty: | |
# ps -A | grep mydeamontest | |
# ls /tmp/mydeamon.* | |
WATCHDOG=$1 | |
echo "$0: started $WATCHDOG" | |
sleep 1 | |
touch $WATCHDOG | |
sleep 1 | |
touch $WATCHDOG | |
sleep 1 | |
touch $WATCHDOG | |
sleep 1 | |
touch $WATCHDOG | |
sleep 1 | |
touch $WATCHDOG | |
while true; do | |
echo "$0: sleep 10" | |
sleep 10 | |
touch $WATCHDOG | |
echo "$0: failed, this script should have been killed" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment