flock blocks until a lock can be obtained (unless you tell it otherwise).
use strict; use warnings; use Fcntl qw( :flock ); sleep(1); open(my $fh, '+<', $0) or die "open: $!\n"; print localtime().": $$'s flock attempt starts\n"; flock($fh, LOCK_EX) or die "flock: $!\n"; print localtime().": $$'s flock obtained\n"; sleep(5); print localtime().": $$ ends\n";
$ for q in 1 2 3 4 ; do perl 807067.pl & done Fri Nov 13 17:21:04 2009: 20079's flock attempt starts Fri Nov 13 17:21:04 2009: 20079's flock obtained Fri Nov 13 17:21:04 2009: 20080's flock attempt starts Fri Nov 13 17:21:04 2009: 20082's flock attempt starts Fri Nov 13 17:21:04 2009: 20081's flock attempt starts Fri Nov 13 17:21:09 2009: 20079 ends Fri Nov 13 17:21:09 2009: 20081's flock obtained Fri Nov 13 17:21:14 2009: 20081 ends Fri Nov 13 17:21:14 2009: 20082's flock obtained Fri Nov 13 17:21:19 2009: 20082 ends Fri Nov 13 17:21:19 2009: 20080's flock obtained Fri Nov 13 17:21:24 2009: 20080 ends

Now try using LOCK_EX | LOCK_NB...

Fri Nov 13 17:26:42 2009: 20116's flock attempt starts Fri Nov 13 17:26:42 2009: 20116's flock obtained Fri Nov 13 17:26:42 2009: 20117's flock attempt starts flock: Resource temporarily unavailable Fri Nov 13 17:26:42 2009: 20118's flock attempt starts flock: Resource temporarily unavailable Fri Nov 13 17:26:42 2009: 20119's flock attempt starts flock: Resource temporarily unavailable

You can detect a denied lock using

use Errno qw( EWOULDBLOCK ); if (flock(..., ... | LOCK_NB)) { lock obtained } elsif ($! == EWOULDBLOCK) { lock denied } else { some error }

Update: Additions.


In reply to Re: flock on Ubuntu 9.10 by ikegami
in thread SOLVED [flock on Ubuntu 9.10] by poctob

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.