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.
On Linux, how can I check to ensure that the PID file exists and if not, execute a command to restart it?
The command would be
python daemon.py restart
which has to be executed from a specific directory.
While checking if a file exists, the most commonly used file operators are -e and -f. The '-e' option is used to check whether a file exists regardless of the type, while the '-f' option is used to return true value only if the file is a regular file (not a directory or a device).
To test if a file does not exist using the “||” operator, simply check if it exists using the “-f” flag and specify the command to run if it fails. [[ -f <file> ]] || echo "This file does not exist!"
You can use the find command and other options as follows. The -s option to the test builtin check to see if FILE exists and has a size greater than zero. It returns true and false values to indicate that file is empty or has some data.
[ -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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With