Any recommendations for cross platform locking?

Alias on 2008-05-21T01:05:09

In the ongoing quest to make all my code run on Windows properly, most of the biggest problems are now solved, at least for my stuff.

But one obvious bug-bear remains, file locking.

File locking is already a bit of a pain, even on Unix. Extend that across all platforms and it becomes horrid.

For example, one of my favourite tricks for (mostly non-cpan) scripts that should only ever run one instance is the DATA lock.

In short, you add a small __DATA__ section to the end of your launch script, and then flock the resulting DATA file-handle.

This works brilliantly, because it relies on the existence of nothing other than the script itself, and the lock automatically cleans up when the script ends, crashes, or the power goes out, etc etc. In my experience of using it, it's the only 100% reliable locking scheme.

But of course it doesn't work on Windows...

And I've never seen any really good locking schemes that worked cross-platform. CPAN.pm's locking method for example is a continuous nightmare of unreliable and stale lock files.

So is there an answer out there that is both completely reliable, works everywhere, and doesn't involve me rolling my own.

What do you use?


inet ports?

ddick on 2008-05-21T01:59:05

seems like a possible option.

DATA

djberg96 on 2008-05-21T04:12:50

Oh, neat trick. I never thought of that, thanks.

BTW, it _should_ work on Windows, though I guess I'd have to see your implementation to understand why it doesn't. Windows does have LockFile and LockFileEx, which is how flock is implemented in Ruby on Windows. I would think Perl would have a very similar implementation.

works for me?????

ddick on 2008-05-21T05:58:33

#! /usr/bin/perl

use Fcntl();

sleep 2;

print "Locking....\n";
unless (flock(DATA, Fcntl::LOCK_EX())) {
    die("Failed to lock:$!");
}
print "Locked.....\n";
sleep 5;

__DATA__

works for me on an XP virtual machine with strawberry perl.

when doesn't it work?

Me too

link on 2008-05-21T08:28:20

Works for me with activeperl 5.8.8 but it is not printing failed to lock. I think the flock stops perl loading the script at all so nothing is executed but it is hard to tell without an error message of some sort.

Sys::RunAlone

jouke on 2008-06-02T13:12:32

Isn't that what Liz's Sys::RunAlone does? ;-)