[Canberra-pm] How to flock a file for to ensure only one CGI BIN script process at a time
Paul Fenwick
pjf at perltraining.com.au
Thu Jul 28 17:55:05 PDT 2005
G'day John,
John.Hockaday at ga.gov.au wrote:
[snip]
> I thought that flock would be the best method to use a lock file to stop any
> other users from running the script while someone else has it running. The
> trouble is that the script creates the lockFile and doesn't delete it. How
> can I get flock to check if the lockFile exists and if so send a busy message
> to CGI. Otherwise, set the lockFile, flock it and process the site?
If I understand you correctly, you only want a single copy of the CGI to be
executing at once. The easy way to do this isn't to create a separate lockfile,
but to instead lock your program itself. These are described in MJD's "Locking
Tricks and Traps" that can be found at http://perl.plover.com/yak/flock/ .
In a nutshell:
use Fcntl qw(:flock);
open(SELF, "< $0") or die "Cannot open $0 - $!\n";
flock(SELF, LOCK_EX | LOCK_NB) or die "Already running\n";
__END__
alternatively:
flock(DATA, LOCK_EX | LOCK_NB) or die "Already Running\n";
# ...
__DATA__
By opening and locking your own source file, you save all the hassle of trying
to co-ordinate lockfile creation and deletion.
All this assumes that you're running on a single machine, and not a farm of
machines. Locking over a network filesystem has other hazards.
Cheerio,
Paul
--
Paul Fenwick <pjf at perltraining.com.au> | http://perltraining.com.au/
Director of Training | Ph: +61 3 9354 6001
Perl Training Australia | Fax: +61 3 9354 2681
More information about the Canberra-pm
mailing list