This script will check to see if a daemon is still running. The daemon name is set in the PROCESS_NAME variable. The pgrep command searches for the process to see if it’s running. If no threads are found then the dameon is started back up and the script exits. In this example the script checks to see if the apache2 daemon is up.
#!/bin/bash
check_process() {
echo "$ts: checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}
while [ 1 ]; do
# timestamp
ts=`date +%T`
PROCESS_NAME="apache2"
echo "$ts: begin checking..."
check_process "$PROCESS_NAME"
if [ $? -eq 0 ];
then
echo "$ts: not running, restarting..." && `/etc/init.d/$PROCESS_NAME start -i > /dev/null`
else
echo "$PROCESS_NAME is already running..."
fi
exit $?
done