How do I write a bash script to restart a process if it dies?

后端 未结 8 2102
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:47

I have a python script that\'ll be checking a queue and performing an action on each item:

# checkqueue.py
while True:
  check_queue()
  do_something()
         


        
8条回答
  •  不知归路
    2020-11-22 03:14

    The easiest way to do it is using flock on file. In Python script you'd do

    lf = open('/tmp/script.lock','w')
    if(fcntl.flock(lf, fcntl.LOCK_EX|fcntl.LOCK_NB) != 0): 
       sys.exit('other instance already running')
    lf.write('%d\n'%os.getpid())
    lf.flush()
    

    In shell you can actually test if it's running:

    if [ `flock -xn /tmp/script.lock -c 'echo 1'` ]; then 
       echo 'it's not running'
       restart.
    else
       echo -n 'it's already running with PID '
       cat /tmp/script.lock
    fi
    

    But of course you don't have to test, because if it's already running and you restart it, it'll exit with 'other instance already running'

    When process dies, all it's file descriptors are closed and all locks are automatically removed.

提交回复
热议问题