One solution is to implement your own flock in terms of fcntl, and keep track of the lock's state. For example, something like:
our @lockstat; sub readlock { my($fh)=@_; my $fileno = fileno($fh); defined($fileno) or die "Bad filehandle"; if ($lockstat[$fileno] && $lockstat[$fileno]{count}) { $lockstat[$fileno]{count}++; } else { fcntl_lock($fh,F_RDLCK); $lockstat[$fileno]{count}=1; } } sub readunlock { my($fh)=@_; my $fileno = fileno($fh); defined($fileno) or die "Bad filehandle"; return unless $lockstat[$fileno] and $lockstat[$fileno]{count}; if (--$lockstat[$fileno]{count} == 0) { fcntl_lock($fh,F_UNLCK); } }

You can expand this to cover write locks in a similar way (or write a general myflock that does both read, write, and unlocks). If you're using multiple threads, you'll need to use mutexes to protect the data structures from the different threads. You'll also have to think about how to deal with close.

I seem to recall that Perl has a compile-time option to use its own flock implementation based on fcntl; you may want to look into that as well.


In reply to Re: Fcntl() and multiple filehandles by sgifford
in thread Fcntl() and multiple filehandles by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.