Thursday, June 23, 2011

The lock sock

While developing a piece of code which requires locking
across processes (not threads) and which runs as nobody
user inside a non-writable chroot I came across the idea
to use abstract UNIX sockets for locking.
The advantage is that it is very easy to implement and use
and you dont need to create a file as you would when using
file based locking. You also dont need to mess with the
SVR4 IPC mechanisms and its portable as well. The idea is as
easy as beautiful so I think I am probably not the first
one abusing UNIX sockets that way. The code is here:

Basically you delegate the atomic lock operation to the
kernel via the bind() syscall since no more than one
process can bind to a given path at the same time. Since
there is no unbind() operation you have to close() the
socket in order to free the lock.