> 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.

I just checked this under linux and solaris with:

        use Fcntl ':flock';

        open F, "+< $0: or die $!;
        flock F, LOCK_EX or die $!;
        flock F, LOCK_EX|LOCK_NB or die $!;
        print "OK\n";

and it OK's on both.  Similarly, 

        use Fcntl ':flock';

        open F, "+< $0" or die $!;
        open G, "+< $0" or die $!;
        flock F, LOCK_EX or die $!;
        flock G, LOCK_EX|LOCK_NB or die $!;
        print "OK\n";

This failus under Linux (which I think is wrong) but OK's on Solaris.
"OK" here means "What you suggested won't work."

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

Perhaps the traditional approach doesn't work.  :)

> 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().  

This on also relies on system creating a new process.  I wasn't sure
what this would do on Win32, VMS, OS390, etc.  Hence my original
question:

>> 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.

Sorry to be so elliptical.  What I should have said was that I can
think of lots of ways to do it but they all involve starting a new
process, and I'm reluctant to start a new prcoess unless I have to,
because I have no idea what it does on Weird Platform X.

Reply via email to