A Simple “bash” Script To Watch Linux Processes

When you have some process in a system that must be kept always running it’s important to use some kind of software watchdog to do this job.

I have some historical data recording processes programmed in QT that run in a Linux machine under the KDE desktop environment. Sometimes there are unexpected crashes caused by network problems or load excess of the database server. So I had to create a software watchdog to restart the process when it closes.

It’s very simple but effective. It simply checks the presence of a process and if it’s not there, executes it.

There are 2 arguments to pass to the script: the first is the name of the executable file and the second is the path to it.

The script chkprocrun.sh is this:

#!/bin/sh
# tests a process running on KDE
# if not found, runs it
# if kde not logged in, just exits
# first argument: name of executable file
# second argument: path to executable file

# check KDE running
RESULT=`pgrep kdeinit4`
if [ "${RESULT:-null}" = null ]; then
echo "KDE not running, exiting..."
 exit
fi
# echo "KDE is running! Will check process." >> /tmp/chkprocrun.log
PROCEXE="$1"
PROCPATH="$2"
# test process running
RESULT=`pgrep -f ${PROCPATH}${PROCEXE}`
if [ "${RESULT:-null}" = null ]; then
 echo `date` " - ${PROCPATH}${PROCEXE} not running, starting it.." >> /tmp/chkprocrun.log
 cd $PROCPATH
# execute the process on display zero of the local machine
 $PROCPATH$PROCEXE -display :0 &
fi

There is a log file to register each process restart.

I configured cron jobs to call the script for each process to be watched, like this:

0-59 * * * * /home/user/chkprocrun.sh watched_proc /home/user/watched_proc_dir/

This cron job will call the chkprocrun script every minute to check for the existence of the watched_proc.

Ricardo Olsen in-2c-14px, MEng. :: https://dscsys.com

Advertisements