25 August 2013

file locks

by mo

flock(2) says:

flock - apply or remove an advisory lock on an open file

A common convention in the unix work is to use file locks as a way to manage exclusive access to a resource. An example of this is when you only want a single instance of an executable to be running. For example your rails server.

In your typical rails app when you run “rails server” a new file is created in tmp/pids called server.pid. This file contains the process id of the currently running rails server, but it also acts as a file lock.

If you try to run a second instance of a rails server from the same rails project, you will see an error message that says “A server is already running. Check …/tmp/pids/server.pid.” This file is used to make sure that only one instance of the rails server is running at a time.

Let’s look at an example:

pidfile = File.open("#{Dir.pwd}/server.pid", 'a')
if pidfile.flock(File::LOCK_EX | File::LOCK_NB)
  abort "Already running..."

In this example, the file called “server.pid” is opened/created. If there is no lock on the file then the current process id is written to the file.

If the file is locked then the process aborts. This ensures that only one instance of this binary is running at any time.


unix 💎