Run cron job only if it isn't already running

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

    # one instance only (works unless your cmd has 'grep' in it)
    ALREADY_RUNNING_EXIT_STATUS=0
    bn=`basename $0`
    proc=`ps -ef | grep -v grep | grep "$bn" | grep -v " $$ "`
    [ $? -eq 0 ] && {
        pid=`echo $proc | awk '{print $2}'`
        echo "$bn already running with pid $pid"
        exit $ALREADY_RUNNING_EXIT_STATUS
    }
    

    UPDATE .. better way using flock:

    /usr/bin/flock -n /tmp/your-app.lock /path/your-app args 
    

提交回复
热议问题