I need to prevent a script from being executed multiple times simultaneously and so flock
seems right up my street.
What I can't figure out is if I need to manually delete the lock file after the completion of the cron job?
I'm using it like this:
# m h dom mon dow user command
*/20 * * * * root /usr/bin/flock -w 0 /var/cron.lock /usr/bin/myscript
This script is also executed on machine startup by upstart (this is where the race condition is).
The file is created ok, but I can't really see how the command knows if the lock is being held by another process. It's empty and monitoring it for changes when the cron job is kicked off produces nothing (using fuser
).
If someone can explain how it works I'd be very appreciative!
/usr/bin/flock -w 0
-w 0
specifies the timeout in seconds 'flock' will wait before if fails if the file cannot be locked.. in this case, it requests that the file lock should be established without waiting, or fail.