Run cron job only if it isn't already running

后端 未结 16 957
执笔经年
执笔经年 2020-11-29 14:53

I\'m trying to set up a cron job as a sort of watchdog for a daemon that I\'ve created. If the daemon errors out and fails, I want the cron job to periodically restart it...

16条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 15:28

    As others have stated, writing and checking a PID file is a good solution. Here's my bash implementation:

    #!/bin/bash
    
    mkdir -p "$HOME/tmp"
    PIDFILE="$HOME/tmp/myprogram.pid"
    
    if [ -e "${PIDFILE}" ] && (ps -u $(whoami) -opid= |
                               grep -P "^\s*$(cat ${PIDFILE})$" &> /dev/null); then
      echo "Already running."
      exit 99
    fi
    
    /path/to/myprogram > $HOME/tmp/myprogram.log &
    
    echo $! > "${PIDFILE}"
    chmod 644 "${PIDFILE}"
    

提交回复
热议问题