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

前端 未结 7 1894
孤独总比滥情好
孤独总比滥情好 2020-11-29 23:38

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: <

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 00:35

    Programs to monitor if a process on a system is running.

    Script is stored in crontab and runs once every minute.

    This works with not running process an to many process:

    #! /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}')
        ;;
    esac
    

    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.

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

    And at last, a one liner

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

    cccam oscam

提交回复
热议问题