in reply to Fork + Flock = Who Gets the Lock?

the above discussion slightly confused me, so I decided to conduct a few tests of my own.

amusingly enough, both Perls on Cygwin and WinXP hang on the following:

#! perl -lw use strict; use Fcntl ':flock'; open my $fh, "<", "whatever" or die $!; flock $fh, LOCK_EX; flock $fh, LOCK_EX;

well, ok, let's try on a better OS.. so, Solaris ( don't flame me, that's the only other I have lying around )

this:

open my $fh, "<", "whatever" or die $!; flock $fh, LOCK_EX; my $pid = open my $pip, "|-"; die "open(): $!" unless defined $pid; if ($pid > 0) { close $pip } else { flock($fh,LOCK_EX); print "got the lock"}
is perfectly fine.. but try to change the open to ">", and the whole thing hangs, clearly as the child waits for the exclusive lock, while the parent waits to close the child... the reverse
if ($pid > 0) { flock($fh,LOCK_EX); print "got the lock" } else { sleep(20) }
works like a charm, the parent grabs the exclusive lock straight away...

Moral: flocks are weird. I will not fork a flock (or flock a fork), unless in dire need of weird behaviour..
update: fixed open fail check, thanks to spotter tlm