On Mon, Mar 18, 2002 at 03:57:55AM -0500, Mark-Jason Dominus wrote:
> Actually that reminds me of another puzzle I have.  My module provides
> an interface to 'flock'.  What is an easy way to check that the file
> is actually being locked?  I put off writing the tests because i did
> not want to fork.

I just thought of a clever way to do it without alarm!  Just use
non-blocking mode.

    lock_file($foo);
    open(FH, $foo);
    ok( !flock(FH, LOCK_NB | LOCK_EX) );

if the flock fails the file is already locked.


The traditional approaches require causing a deadlock and breaking it
with alarm.

    my $start = time;
    lock_file($foo);
    eval {
        local $SIG{ALRM} = sub { die "ALARM!\n" };
        alarm 5;
        lock_file($foo);
        alarm 0;
    };
    is( $@, "ALARM\n" );
    can_ok( time, '>', $start + 3,  'Locking works' );

I check both the time and the alarm for thoroughness.  I have had a
few issues with this on 5.6.0 where, for some odd reason, everything
dies correctly but the "ALARM!\n" message goes to STDERR and not to
$@.  I can't duplicate it outside the context of a single program, so
you might be safe.

So here's the other way.  We cause a deadlock using another process
which kills itself after a certain amount of time.

    my $start = time;
    lock_file($foo);
    system($^X, '-e', 'use Whatever;  alarm 5;  lock_file($foo)');
    cmp_ok( time, '>', $start + 3,     'Locking works' );

again, these all rely on alarm().  



> Is this mailing list the right place to ask "how do I test for X"
> questions?  Or would the module-authors list be more appropriate?

This is the right place.  I'm keeping track of the questions &
answers, someday there will be a FAQ.


-- 

Michael G. Schwern   <[EMAIL PROTECTED]>    http://www.pobox.com/~schwern/
Perl Quality Assurance      <[EMAIL PROTECTED]>         Kwalitee Is Job One
My lips, your breast and a whole lotta strange arguing.

Reply via email to