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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.