Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there a way to tell flock to try to lock the file over and over untill it gets it locked?
The way I have always done it is something like this:
FLOCK: do { open (FILE, ">file.dat"); flock(FILE, 2) or redo FLOCK; print FILE "blah\n"; close FILE; $locked = 1; } while ($locked =/ 1)
is there a simpler way to do this? I want something that will be generous enough to not lock up the entire program if it can't lock one file, but I also want it to be able to retry if someone else has it locked at the moment.

Replies are listed 'Best First'.
Re: flock till ya get it right
by merlyn (Sage) on Nov 04, 2001 at 02:21 UTC
    Unless you use the nowait value (with 8), flock blocks until it's flocked, or until it would never have flocked (file not found, or no permissions to do such, for example).

    No loop needed here.

    But you also don't want to flock after opening for writing like that. You've just clobbered the file even if someone is using it!

    -- Randal L. Schwartz, Perl hacker

Re: flock till ya get it right
by dws (Chancellor) on Nov 04, 2001 at 02:23 UTC
    Why reopen the file if your object is to get a lock? Try something like:
    open(FILE, ">file.dat") or die "file.dat: $!"; while ( ! flock(FILE, 2) ) { # you *might* want to consider bailing out at # some point. } truncate FILE, 0; # important! to avoid corrupted files print FILE, "blah\n"; close(FILE); }
    The truncate call is there to avoid the nasty race condition that happens when someone else manages to also open the file for writing and then writes into it prior to your getting the lock.