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

后端 未结 7 1457
星月不相逢
星月不相逢 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.

    0 讨论(0)
  • 2020-12-30 21:43
    ls /tmp/filename.pid
    

    It returns true if file exists. Returns false if file does not exist.

    0 讨论(0)
  • 2020-12-30 21:45
    [ -f /tmp/filename.pid ] || python daemon.py restart
    

    -f checks if the given path exists and is a regular file (just -e checks if the path exists)

    the [] perform the test and returns 0 on success, 1 otherwise

    the || is a C-like or, so if the command on the left fails, execute the command on the right.

    So the final statement says, if /tmp/filename.pid does NOT exist then start the daemon.

    0 讨论(0)
  • 2020-12-30 21:51
    test -f filename && daemon.py restart || echo "File doesn't exists"
    
    0 讨论(0)
  • 2020-12-30 21:53

    If it is bash scripting you are wondering about, something like this would work:

    if [ ! -f "$FILENAME" ]; then
       python daemon.py restart
    fi
    

    A better option may be to look into lockfile

    0 讨论(0)
  • 2020-12-30 21:54

    You can also use a ready solution like Monit.

    0 讨论(0)
提交回复
热议问题