Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

Re: Preventing multiple instances

by davido (Cardinal)
on Dec 17, 2020 at 21:29 UTC ( [id://11125368]=note: print w/replies, xml ) Need Help??

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;


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 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.


Replies are listed 'Best First'.
Re^2: Preventing multiple instances
by hippo (Bishop) on Jun 03, 2021 at 13:31 UTC
    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; }; }

    I am confused by there being a do { warn "XXX"; exit; } in this snippet rather than a simple die "XXX", especially seeing as how you are calling die if the open fails in the preceding statement. Would you be so kind as to explain the reasoning, please?


      Good question.

      My thought process when I wrote that was that having the process already running wasn't an exceptional event. It might be noteworthy, but not worthy of a non-zero exit code. But that's entirely subjective to the use-case. I had recently been working on something where it was fairly normal behavior for an instance already to be running, and for that to be a perfectly acceptable situation.

      So that's really it. A die would be fine too, but would (on a POSIX system) result in an 11 exit code, resource temporarily unavailable. By separating the message from the termination I went the other direction where the exit code is zero, while STDERR still gets a little quip.


Re^2: Preventing multiple instances
by sleet (Beadle) on Nov 19, 2022 at 23:12 UTC
    Note that the lock will silently be released if you edit the file while it is running, since flock creates an advisory lock (meaning it can be ignored).

      The lock is coterminous with the open filehandle / file descriptor unless released by LOCK_UN. A write by a process that ignores the lock doesn't release the lock, it just ignores it (which and breakage can occur). A write by the process that holds the lock also would not release the lock.

      At least that's my recollection. The rules can be tricky though. And the fact that locks are advisory is both powerful and scary.


Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11125368]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (8)
As of 2024-04-19 08:55 GMT
Find Nodes?
    Voting Booth?

    No recent polls found