I’m sure there’s a million variants out there, but I had a simple need to make sure a process was running and restart it if it isn’t. I’ve done this before using one off scripts, but then I figured I may as well do one that is generic:
watchdog.sh:
#!/bin/sh
# watchdog LOOKFOR SERVICE
# will restart SERVICE (/sbin/service SERVICE restart) when LOOKFOR doesn’t appear in the processlist
P=`echo $1 | sed ‘s/^\(.\)/[\1]/’` # enclose first char in brackets
ps -ef | grep -v $0 | grep -q “$P” # skip myself
if [ $? -eq 1 ]; then
/sbin/service $2 restart
fi
So,
/usr/local/sbin/watchdog.sh asterisk asterisk
will run /sbin/service asterisk if there are no asterisk processes running.