in reply to Order of flock and open

I'm surprised no one has pointed you to sysopen(), rather than the simpler open() function.

From the perlopentut tutorial:

To get an exclusive lock, typically used for writing, you have to be careful. We sysopen the file so it can be locked before it gets emptied. You can get a nonblocking version using LOCK_EX | LOCK_NB.
use 5.004; # make sure you have at least this level perl use Fcntl qw(:DEFAULT :flock); sysopen(FH, "filename", O_WRONLY | O_CREAT) or die "can't open filename: $!"; flock(FH, LOCK_EX) or die "can't lock filename: $!"; truncate(FH, 0) or die "can't truncate filename: $!"; # now write to FH

[Jon]

Replies are listed 'Best First'.
Re: Re: Order of flock and open
by mdog (Pilgrim) on May 01, 2003 at 20:33 UTC
    Personally, I like LockFile::Simple.

    Works great for me...
    use LockFile::Simple qw(lock trylock unlock); $lockmgr = LockFile::Simple->make(-format => '%f.lck', -max => 20, -delay => 1, -stale => 1); # first program to get the lock the file gets the chance to run it + if($lockmgr->trylock("$eventsLogFile")){ my @bytes= split(//, $serial_data); $lockmgr->unlock("$eventsLogFile"); }