On Mon, Mar 18, 2002 at 11:14:59AM -0500, Mark-Jason Dominus wrote:
> > I just thought of a clever way to do it without alarm!  
> 
> So clever, it doesn't work!
> 
> >     lock_file($foo);
> >     open(FH, $foo);
> >     ok( !flock(FH, LOCK_NB | LOCK_EX) );
> 
> Seriously, on most unix systems, the following:
> 
>         flock(FH, LOCK_EX);
>         flock(FH, LOCK_EX|LOCK_NB) or die;
> 
> doe *not* die.  A process is allowed to ask for (and obtain) an
> exclusive lock on a file if it already has a lock on that same file.
> There's no deadlock at all.

Oh dear, never knew that.

Ok, how about some variant on this:

    BEGIN {
        *CORE::GLOBAL::flock = sub (*$) {
            my($fh, $flag) = @_;

            $Locks{fileno $fh}++;
            return flock $fh, $flag;
        };
    }

I'm going to have to hand-wave a bit at this point.  You'll likely
have to tie any handle that goes through flock() so you can check if
it was CLOSEd or DESTROYed (and thus releases the lock).

The idea is you can know when flock() has been called, on what fileno
and with what flags, and also when locks have been implicitly released.

A variant on that might be if you already have internal _lock() and
_unlock() functions.

    {
        my $orig_lock   = \&Your::Module::_lock;
        my $orig_unlock = \&Your::Module::_unlock;

        no warnings 'redefine';

        sub Your::Module::_lock {
            my($file) = @_;

            $Locks{$file}++;
            goto &$orig_lock;
        }

        sub Your::Module::_unlock {
            my($file) = @_;

            $Locks{$file}--;
            goto &$orig_lock;
        }


        do_something_that_should_result_in_a_lock($file);
        is( $Locks{$file}, 1 );
        ...whatever else...

        *Your::Module::lock   = $orig_lock;
        *Your::Module::unlock = $orig_unlock;
    }

Sorry I can't be more specific.


-- 

Michael G. Schwern   <[EMAIL PROTECTED]>    http://www.pobox.com/~schwern/
Perl Quality Assurance      <[EMAIL PROTECTED]>         Kwalitee Is Job One
Realize this, sweetheart, I'm squeezing my poodle.

Reply via email to