Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

Alias (5735)

Alias
  (email not shown publicly)
http://ali.as/

Journal of Alias (5735)

Tuesday May 20, 2008
08:05 PM

Any recommendations for cross platform locking?

[ #36478 ]

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?

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • seems like a possible option.
  • 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.

  • #! /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?

  • 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.
  • Isn't that what Liz's Sys::RunAlone does? ;-)