in reply to flock(), dodgy return?

Hi. Wow what a mess! Try this to open a file with an exclusive lock.
use strict; use warnings; use Fcntl qw(:DEFAULT :flock); sysopen(my $fh, 'filename', O_RDWR | O_CREAT) or die "Can't sysopen"; flock($fh, LOCK_EX) or die "Can't get lock"; print "OK - opened file with lock in place.\n";
You don't need to use a 'semaphore' file to lock a single file. Also, it's probably best to let 'flock' do it's job, rather than putting it in a loop and trying over and over. For lots more info see the 'File Locking' section of The Camel book!

Replies are listed 'Best First'.
Re^2: flock(), dodgy return?
by ikegami (Patriarch) on Aug 01, 2007 at 14:31 UTC
    I suspect alarm will do the trick if a timeout is desired, at least on a unix host.

      Yeah but that brings in more complexity than is really warrented in this situation, no?

Re^2: flock(), dodgy return?
by danstuken (Novice) on Aug 01, 2007 at 14:35 UTC

    Thanks oxone,

    I agree with you, its a bit of a state - rest assured it wont end that way. The semaphore was a product of desperation. Its been the sort of week where everything has gone wrong (and its only wednesday!?) and so I was kinda scrabbling at the problem rather than calmly dealing with it.

    With regards to not using LOCK_NB, I don't think I can go that way. This script is called, eventually, from a GUI app and I'd rather not leave the user hanging on indefinitely, even if in 99.99% of cases the lock will only exist for fractions of a second. I keep coming over sysopen but have never used it - tbh open() works fine and is what all the scripts here use and I'd rather not move away from that.