Flock to get a lock

LockIf you want to ensure that a process is not running twice at the same time on Linux, there is a tool, probably included in your distribution, called Flock.

The command

You can find many usage on the web and in man but the only one I am using is the most basic one

Options

  • x means Exclusive lock
  • n means Stop if locked (if you ommit it, the second execution will wait for the first to end) and returns status 1

/tmp/my-lock.lock is the lock file. Generally, you will put it in tmp folder and give a recognizable name

-c is the command to run, here just sleep for 10 s

If you open 2 terminal windows and launch the command in both, you will see that the first one will wait 10s, the second one will give you back the hand instantly.

For which purpose ?

The main usage I found is for frequent cron.

1st example

You use the system cron for WordPress cron. If you setup the cron to run every 1mn, you want to be sure to not launch 2 wp-cron if one takes more than 1minute to execute (for an upgrade for example).

See How to use linux cron for WordPress article.

2nd example

I used it several years ago for a “service simulation”. I had a PHP script scanning a queue for new events. This script was essentially a loop querying the queue, doing its stuff and re-querying the queue.

I wanted

  • to have the script running at server restart
  • to be able to stop the script in an elegant way (and in a stable state)
  • to be able to restart the script every x hours to ensure no memory leak (not sure about PHP 😉 )

What I did

  • a php script with a loop
    • at each start of the loop, ensure that a file “stop” is not present. If it is, end the script.
    • at each start of the loop, ensure that it has not passed more than X hours since start. If it is, end the script.
  • the script was launched by a cron every minute with a flock
    • This way, if the script is already running, the cron is doing nothing
    • if the script stopped because of the number of hours since start (or any crash, or system restart), it is relaunched
    • if the script stopped because of the “stop” file, it exits instantly

I just simulated the execution of a background script with PHP, Cron and Flock.

Tags:, , ,