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

Hi all I am experimenting with file locking on Linux/HPUX/SunOS. It works OK on Linux, but HPUX and SunOS seem to be rather ignorant of shared locks (LOCK_SH), while exclusive locks work fine. For instance:
Process 1: open FH, ">lock" or die "Cannot >lock"; flock( FH, LOCK_SH );
A while after...
Process 2: open FH, ">lock" or die "Cannot >lock"; flock( FH, LOCK_EX );
This while cause Process 2 to wait for Process 1 to unlock FH on Linux, but not on HPUX and SunOS. Using a LOCK_EX instead of LOCK_SH cause Process 2 to wait on HPUX and SunOS which is the expected result.

Now my questions are:
- is that feature something know ? ( I have not found any clue about that in perlport).
- is there a way to emulate properly flock on HPUX and SunOS.

Thanks

Replies are listed 'Best First'.
(tye)Re: flock on differents OSes
by tye (Sage) on Dec 20, 2001 at 22:15 UTC

    Trying to reproduce this under HPUX (which I was able to do), I see that the second flock() fails with $! of "Bad file number" [even though fileno(FH) reports 3]. Smells like a bug in Perl's emulation of flock() using fcntl() locking [since HPUX doesn't have native flock()]. I think I'll dig some more...

    Update! Here is the reason. Quoting "man fcntl":

    The file descriptor on which a read lock is being placed must have been opened with read access.

    So, since you don't open FH for read access, you can't get an emulated LOCK_SH on it at all. I wonder if Perl documents this... (nope, it doesn't -- time to write a patch).

    So, of course, the work-around is to open "+>lock" instead.

            - tye (but my friends call me "Tye")
Re: flock on differents OSes
by virtualsue (Vicar) on Feb 11, 2002 at 13:46 UTC
    You might find this tutorial useful: File Locking, particularly the responses by KM.

    In my view Perl on SunOS/Solaris is behaving fairly rationally when it dies on an attempt to take a LOCK_SH on a file opened for write. Why would you want to allow others to take locks on a file that you are modifying?

Re: flock on differents OSes
by gellyfish (Monsignor) on Feb 11, 2002 at 11:34 UTC

    In addition to what tye said, you should bear in mind that a shared lock is probably not what you want when you are going to write to a file - this is is probably why those OS are behaving like that.

    /J\