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

前端 未结 7 1884
孤独总比滥情好
孤独总比滥情好 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:31

    If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:

    #! /bin/bash
    
    logfile="/var/oscamlog/oscam1check.log"
    
    case "$(pidof oscam1 | wc -w)" in
    
    0)  echo "oscam1 not running, restarting oscam1:     $(date)" >> $logfile
        /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
        ;;
    2)  echo "oscam1 running, all OK:     $(date)" >> $logfile
        ;;
    *)  echo "multiple instances of oscam1 running. Stopping & restarting oscam1:     $(date)" >> $logfile
        kill $(pidof oscam1 | awk '{ $1=""; print $0}')
        ;;
    esac
    

    It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like

    root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript

    Just an FYI

提交回复
热议问题