linuxnoob linuxnoob - 10 months ago 44
Linux Question

Linux Script to check if process is running & act on the result

I have a process that fails regularly & sometimes starts duplicate instances..

When I run:

ps x |grep -v grep |grep -c "processname"

I will get:

This is normal as the process runs with a recovery process..

If I get

I will want to start the process
if I get:

I will want to stop & restart the process

What I need is a way of taking the result of
ps x |grep -v grep |grep -c "processname"

Then setup a simple 3 option function

ps x |grep -v grep |grep -c "processname"
if answer = 0 (start process & write NOK & Time to log /var/processlog/check)
if answer = 2 (Do nothing & write OK & time to log /var/processlog/check)
if answer = 4 (stot & restart the process & write NOK & Time to log /var/processlog/check)

The process is stopped with
killall -9 process

The process is started with
process -b -c /usr/local/etc

My main problem is finding a way to act on the result of
ps x |grep -v grep |grep -c "processname"

Ideally, I would like to make the result of that grep a variable within the script with something like this:

process=$(ps x |grep -v grep |grep -c "processname")

If possible.


Here is a script I use to monitor if a process on a system is running.
Script is stored in crontab and runs once every minute.

#! /bin/bash

case "$(pidof amadeus.x86 | wc -w)" in

0)  echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt
    /etc/amadeus/amadeus.x86 &
1)  # all ok
*)  echo "Removed double Amadeus: $(date)" >> /var/log/amadeus.txt
    kill $(pidof amadeus.x86 | awk '{print $1}')

0 If process is not found, restart it.
1 If process is found, all ok.
* If process running 2 or more, kill the last.

A simpler version. This just test if process is running, and if not restart it.
It just tests the exit flag $? from the pidof program. It will be 0 of process is running and 1 if not.

pidof  amadeus.x86 >/dev/null
if [[ $? -ne 0 ]] ; then
        echo "Restarting Amadeus:     $(date)" >> /var/log/amadeus.txt
        /etc/amadeus/amadeus.x86 &