Run cron job only if it isn't already running

后端 未结 16 927
执笔经年
执笔经年 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:36

    I'd suggest the following as an improvement to rsanden's answer (I'd post as a comment, but don't have enough reputation...):

    #!/usr/bin/env bash
    
    PIDFILE="$HOME/tmp/myprogram.pid"
    
    if [ -e "${PIDFILE}" ] && (ps -p $(cat ${PIDFILE}) > /dev/null); then
      echo "Already running."
      exit 99
    fi
    
    /path/to/myprogram
    

    This avoids possible false matches (and the overhead of grepping), and it suppresses output and relies only on exit status of ps.

提交回复
热议问题