Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Flock and Subroutine

by bichonfrise74 (Vicar)
on Mar 04, 2010 at 21:06 UTC ( [id://826813]=perlquestion: print w/replies, xml ) Need Help??

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

The code below prevents having itself run more than once. The code is working in the sense that if you try to run it more than once, you will get a message of 'Another $script is already running.'.

But if you uncomment the "Check_Race_Condition()", and comment out the lines following it -- "open and flock", and try to run the code more than once, it will not give any error message. This means that the script is able to run more than once.

I'm not sure why this is happening... Am I missing something obvious?
#!/usr/bin/perl use warnings; use strict; use Fcntl qw( :flock ); print "Script $0 is running now.\n"; # 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"); 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"); }

Replies are listed 'Best First'.
Re: Flock and Subroutine
by kennethk (Abbot) on Mar 04, 2010 at 21:15 UTC
    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; }
Re: Flock and Subroutine
by scorpio17 (Canon) on Mar 04, 2010 at 22:20 UTC
Re: Flock and Subroutine
by Khen1950fx (Canon) on Mar 05, 2010 at 07:17 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://826813]
Approved by kennethk
Front-paged by kennethk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (4)
As of 2024-04-19 04:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found