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

sub sleep_lock { my $FH = *{$_[0]}; my $lock_type = $_[1]; my $time = $_[2] ||5; for ( 1..$time ) { last if flock $FH, $lock_type; unless ( $_ < $time ) { die "Can't lock file: $!" }; sleep 1; } }
This code is my attempt to create a more robust locking mechanism. Is there anyway I can get the filename from the filehandle? I could pass it in as a parameter, but I'd rather pass as few parameters as possible.

Are there any other problems anyone sees?

Replies are listed 'Best First'.
Re: Filename from filehandle?
by clintp (Curate) on Apr 24, 2001 at 04:29 UTC
    In general, you can't get a filename from a filehandle. What name would you use if STDIN were passed? :)

    >Are there any other problems anyone sees?

    Possibly the use of $lock_type. It looks like you're assuming that the flock() will fail if the file is already locked. That's true only on non-blocking filehandles or using LOCK_NB or'd with the second argument of flock(). Otherwise it's going to stop there and wait for the lock until it's available.

    And beware of flock'ing filehandles that are already open...

      Could you talk more about "And beware of flock'ing filehandles that are already open... "?

      I don't think I've ever applied a lock routine more than once. But now you've got my curiousity. What symptoms might occur if at some point I mess up and flock a file for the second time.

      Sign me curious
      Claude

        Here is the idea of what can happen:
        STEP 1: Wait for the first lock to be lost. STEP 2: Lose the first lock STEP 3: (Why don't we get here?)...
        This state of affairs is known as a "deadlock" and is usually considered Not Good.
        Filehandles that are already opened (especially for writing) have may have already been modified, before the lock was applied. Consider:
        open(FOO, ">/tmp/foo") || die; # You've altered the file! flock(FOO, LOCK_EX) || warn; # And now you bother to lock it?
        Yeah, it's silly. But you'd be amazed at how often it happens.