Linux – using flock with cron

cronlinux

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!

Best Answer

The lock file you specify as the option to /usr/bin/flock; /var/cron.lock remains locked with the flock(2) system call for the duration of your script /usr/bin/myscript. Once your script completes that lock is again released by /usr/bin/flock.

When the /usr/bin/flock command can't achieve a lock, , i.e. because /var/cron.lock is already locked because your script is still running (or any other error condition), /usr/bin/flock won't execute your script. Your script doesn't need to be modified and does not need to do any checking of the lock, that's all done by /usr/bin/flock.

The lock file itself will be created as an empty file by the /usr/bin/flock command if it does not yet exist, but after it has been created the lock file doesn't change, only an flock(2) will be applied and removed. The file won't be removed after your script completes.