Christophe Casalegno

How to check automatically if a process is running and restart it if necessary

Sometimes, you need to check if a particular process is running, and restart him automatically. For this you can use systems like init or svc but you can also make this for a better personal control with the Unix / Linux shell. For this example, i am checking for apache2 but you can replace by the process and the restart command you wants. Place to the code :


#!/bin/sh
# check.sh by Brain 0verride aka Christophe Casalegno
# https://www.christophe-casalegno.com | https://www.christophe-casalegno.com

# Name of the processus to monitor

pcs="apache2"

# Restart command : example : service bind start, service httpd start, etc.

restart="service apache2 start"

# Time to sleep before recheck
sbc=3

# Function to check if the process is running

check_process() {
echo "$tstamp : checking $1"
[ "$1" = "" ] && return 0
[ `pgrep -n $1` ] && return 1 || return 0
}

while [ 1 ]; do
tstamp=`date +%T` #Define timestamp

# Execute checking

echo "$tstamp : checking if the process running..."
check_process $pcs

# If process don't running execute $restart command
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `$restart`
sleep $sbc

done


You can test it with ./pcheck.sh

If the script working fine you will have a screen like this :


14:51:40 : checking if the process running...
14:51:40 : checking apache2
14:51:43 : checking if the process running...
14:51:43 : checking apache2
14:51:46 : checking if the process running...
14:51:46 : checking apache2


If your process is down, then you can see something like this :


14:53:36 : checking if the process running...
14:53:36 : checking apache2
: not running, restarting...
14:53:41 : checking if the process running...
14:53:41 : checking apache2
14:53:44 : checking if the process running...
14:53:44 : checking apache2


You can also easily add others command like send you an email alert, etc.

You can download this script directly from : https://www.christophe-casalegno.com/tools/pcheck.sh

For running this script in bg mode you can use nohup (#nohup ./pcheck.sh& or simply use screen.


Christophe Casalegno
https://twitter.com/Brain0verride

Leave a Comment