in reply to Re: Ensuring only one copy of a perl script is running at a time
in thread Ensuring only one copy of a perl script is running at a time
The problem is that Windows uses mandatory locking, while unix uses advisory locking. It has nothing to do with DATA. Perl doesn't check if the file is locked, so advisory locks are completely ignored. However, when mandatory locking is involved, perl can't read the source file when it's locked.
DATA is a filehandle to the file being executed. It's well known that one can seek to offset 0 of DATA to read the source code. Locking DATA is the same thing as locking the file whose name is in $0. It doesn't matter how you lock the script (using DATA or $0 (as shown below)), the problem still exists.
use strict; use warnings; use Fcntl qw(:flock); print "start of program\n"; open(my $script_fh, '<', $0) or die("Unable to open script source: $!\n"); unless (flock($script_fh, LOCK_EX|LOCK_NB)) { print "$0 is already running. Exiting.\n"; exit(1); } print "sleeping 15...\n"; sleep(15); print "end of program\n"; __DATA__ This exists so flock() code above works. DO NOT REMOVE THIS DATA SECTION.
Update: Updated the non-code portion for clarity.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^3: Ensuring only one copy of a perl script is running at a time
by sruthikuppam (Initiate) on Mar 24, 2011 at 05:24 UTC | |
by ikegami (Patriarch) on Mar 24, 2011 at 18:12 UTC | |
Re^3: Ensuring only one copy of a perl script is running at a time
by Moron (Curate) on Dec 19, 2006 at 17:57 UTC | |
by ikegami (Patriarch) on Dec 19, 2006 at 18:12 UTC | |
by tye (Sage) on Dec 19, 2006 at 18:41 UTC | |
by ikegami (Patriarch) on Dec 19, 2006 at 18:59 UTC |