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

Greetings, follow Monks.

I've been tinkering with some code which flock()s a semaphore file.

With some help from bart in the CB, it appears that shared locks are not available. To quote perldoc -f flock:

Note that the emulation built with lockf(3) doesn't provide shared locks, and it requires that FILEHANDLE be open with write intent. These are the semantics that lockf(3) implements. Most if not all systems implement lockf(3) in terms of fcntl(2) locking, though, so the differing semantics shouldn’t bite too many people.
Unfortunately, I seem to have been bitten. I need both exclusive (LOCK_EX) and shared locks (LOCK_SH).
Changing the permissions on the open statement also causes exclusive locks to fail, as foretold by the perldoc.

I tried recompiling my Perl binary with sh Configure -Ud_flock, but the problem persists.

The test code is shown below. It works as expected on Linux, but not Solaris. I have tried both 5.6.1 and 5.8.0.

On Solaris, the code fails with a Bad file number error.

#!/usr/bin/perl use strict; use warnings; use Fcntl qw(:flock); my $file = shift; open (F, "> $file") or die "Unable to open $file: $!"; my $lock_p = flock(F, LOCK_SH | LOCK_NB); if ($lock_p) { print "Got shared lock on semaphore file!"; my $wait = <>; # For testing - hold lock. flock(F, LOCK_UN) or warn "Problems unlocking $file: $!"; exit 0; } else { die "Ack! Didn't get a shared lock on $file: $!"; }

My questions are as follows:

Cheers in advance,

BazB


If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
That way everyone learns.

Replies are listed 'Best First'.
Re: Shared flocks on Solaris?
by bluto (Curate) on May 07, 2003 at 17:26 UTC
    Your code works fine for me on Solaris if I open the file for reading rather than writing (i.e. use "< $file") assuming the file already exists of course. The Solaris man page I have access to seems to indicate you must open the file for reading to use shared locks. You may want to explore opening the file for read and write if you need both kinds of locks. Update: In other words, try something like "+< $file" or use sysopen() and it's ilk instead.

    bluto

      It's always obvious when you know how to do it :-)

      bluto++ is right.

      After I reinvented the wheel using some C and the wonderful Inline::C, and more importantly spent more time grokking manpages, bluto came along and fixed my silly mistake :-).


      If the information in this post is inaccurate, or just plain wrong, don't just downvote - please post explaining what's wrong.
      That way everyone learns.

Re: Shared flocks on Solaris?
by Anonymous Monk on May 07, 2003 at 21:35 UTC
    OK!