Saturday, March 3, 2012

Re: [nslu2-linux] Re: Lockfiles

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.11 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/

iD8DBQFPUgdif9E0noFvlzgRAtdtAJ9uTBm8vfFPbgqFgPesNct6AJ5BhQCdGC6Y
oqHTcV4HOAySOrta+cjfr0A=
=0CuS
-----END PGP SIGNATURE-----
On 02/03/12 22:11, rolandkbs wrote:
> Creating a file and checking for its presence is not an atomic operation.

Actually...

There's a long and honoured art of using the filesystem for locking,
using mkdir(2) and rmdir(2), like this:

while (mkdir("/tmp/lockfile", 0700) == -1) // try to take lock
{
// if mkdir failed, the lock is already taken, so wait and try
// again
sleep(1);
}

// lock now taken
... do something ...
rmdir("/tmp/lockfile"); // release lock

You can even do this from shell scripts; see lockfile(1).

Of course, named semaphores (see sem_open(3) for details) are better in
every possible way, but there are still cases (e.g. mailboxes, or doing
things from scripts) where the above approach is suitable.

--
┌─── dg@cowlark.com ───── http://www.cowlark.com ─────

│ "Never attribute to malice what can be adequately explained by
│ stupidity." --- Nick Diamos (Hanlon's Razor)

No comments:

Post a Comment