How can I check a file exists and execute a command if not?

后端 未结 7 1492
星月不相逢
星月不相逢 2020-12-30 21:35

I have a daemon I have written using Python. When it is running, it has a PID file located at /tmp/filename.pid. If the daemon isn\'t running then PID file doesn\'t exist.

7条回答
  •  無奈伤痛
    2020-12-30 21:41

    Another approach to solving the problem is a script that ensures that your daemon "stays" alive...

    Something like this (note: signal handling should be added for proper startup/shutdown):

    $PIDFILE = "/path/to/pidfile"
    
    if [ -f "$PIDFILE" ]; then
        echo "Pid file exists!"
        exit 1
    fi
    
    while true; do
        # Write it's own pid file
        python your-server.py ;
    
        # force removal of pid in case of unexpected death.
        rm -f $PIDFILE;
    
        # sleep for 2 seconds
        sleep 2;
    
    done
    

    In this way, the server will stay alive even if it dies unexpectedly.

提交回复
热议问题