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 :
# check.sh by Brain 0verride aka Christophe Casalegno
# https://www.christophe-casalegno.com | https://www.christophe-casalegno.com
# Name of the processus to monitor
# Restart command : example : service bind start, service httpd start, etc.
restart="service apache2 start"
# Time to sleep before recheck
# Function to check if the process is running
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..."
# If process don't running execute $restart command
[ $? -eq 0 ] && echo "$ts: not running, restarting..." && `$restart`
You can test it with
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.