http://www.perlmonks.org?node_id=11125368


in reply to Preventing multiple instances

MJD's "flock" talk (File Locking -- Slides) uses these techniques:

open SELF "< $0" or die ...; flock SELF, LOCK_EX | LOCK_NB or exit;

...or...

flock DATA, LOCK_EX | LOCK_NB or exit; ... __DATA__

More complete examples of these techniques, slightly modernized:

Lock the program name:

#!/usr/bin/env perl use strict; use warnings; use Fcntl qw(:flock); my $highlander; BEGIN { open $highlander, '<', $0 or die "Couldn't open $0: $!\n"; flock $highlander, LOCK_EX | LOCK_NB or do { warn "There can only be one $0\n"; exit; }; } # Other use statements... # code...

Or using the DATA trick:

#!/usr/bin/env perl use strict; use warnings; use Fcntl qw(:flock); flock DATA, LOCK_EX | LOCK_NB or do { warn "There can only be one $0.\n"; exit; }; # Code... # Do not remove double-underscore DATA tag. It is required for highlan +der process assertion. __DATA__

That second version seems more clever (and mostly in a good way), and simpler, but has one disadvantage. If your use statements are loading a lot of code, or code that has compiletime side effects, it's not a good solution because it cannot be put into a BEGIN block. Putting it into a BEGIN block means the flock on the DATA handle gets parsed, and attempts to run, before Perl has had a chance to scan through the rest of the source code file. That means __DATA__ will not have been seen yet, and thus, you would get "flock() on unopened filehandle DATA at mytest.pl line 8.", or something similar. To understand why, consider what a BEGIN block does; as perl is reading through the source file, it runs each 'use' during compiletime as they're seen. If a BEGIN is seen, that is run in the compiletime phase too. This is done line by line, as the source file is read. Eventually perl reads through the file and finds the __DATA__ line. At that point, the DATA handle is created and opened. But any BEGIN blocks would not have access to that handle, because it just hasn't been seen by perl, and hasn't been activated.

The reason we even care about putting the highlander assertion into a BEGIN block is to allow perl to exit before it does unnecessary work. Reading through the source code file is trivial work. But loading other modules could amount to more significant burden, and could also have side effects that take place immediately, which may be undesirable if there is already another copy of this script running.

So if the first solution works for your operating system, it's probably preferable for non-trivial scripts. For simple scripts without a lot of startup dependencies, the DATA one is nice for its elegance.


Dave