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.


Anonymous said...

Abstract Unix sockets are also used by dbus, its nice to not care about cleaning up files in case you got killed by someone else ;)

Anonymous said...

Oh my God, it's C++, it burnt my eyes!

Sean said...

A pipe can also make a great semaphore. Parent makes pipe, forks, and selects forever on the pipe. Any of the children can then write a single byte on the pipe to wake the parent.

Anonymous said...

Yeah, we've been using sockets for locking between processing for a while now. It works cleanly. It's not as atomic as some other approaches, but for processes, it's works well enough.

phoenix_frozen said...

It works, but does it perform? I would have thought that having to go through the socket subsystem would be a lot slower than, say, futexes or semaphores.

David Andrews said...

You can also just use pthreads, as a colleague of mine pointed out to me the other day:

pthread_mutexattr_t l_attr;
pthread_mutexattr_setpshared(&l_attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&my_mutex, &l_attr);

If my_mutex resides in say, a shared mmap, two processes can use it for locking with what you would assume would be similar performance to normal pthread mutexes.


Anonymous said...

WoW, i skimmed the code, and the first thought I had was:

This isn't thread safe! What if a lock call happens in the middle of an unlock. How could you create a thread un-safe locking mechanism ... Oh ... its not meant for multi-threaded code.