You are having a scoping issue. Because you are using lexically-scoped indirect file handles ( my $self) instead of either a global or bareword, your file handle is going out of scope when the subroutine returns. When it goes out of scope, Perl cleans it up by releasing the flock and closing the file. A quick fix for what you posted is to move your sleep operation into your subroutine. Given that probably defeats your ultimate goal, however, might I suggest returning the file handle and holding onto it in the main script, a la:
#! /usr/bin/perl
use strict;
use warnings;
use Fcntl qw( :flock );
print "Script $0 is running now.\n";
my $lock = Check_Race_Condition();
sleep( 100 );
print "End.\n";
sub Check_Race_Condition {
open( my $self, '<', $0 )
or die( "Another $0 is already running.\n");
flock( $self, LOCK_EX | LOCK_NB )
or die( "Another $0 is already running.\n");
return $self;
}
-
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.
|