in reply to Mechanism for ensuring only one instance of a Perl script can only run?

See the highlander script. The basic idea is to flock() your program script. That way, the lock is automatically released once your program ends (or crashes).

  • Comment on Re: Mechanism for ensuring only one instance of a Perl script can only run?

Replies are listed 'Best First'.
Re^2: Mechanism for ensuring only one instance of a Perl script can only run?
by redapplesonly (Sexton) on Dec 02, 2022 at 17:04 UTC
    Thanks Corion! So one caveat I have is that if a newly-executed script realizes that there's another instance already at work, I want the new script to terminate immediately, not enter a queue to run later. It looks like flock() doesn't offer a "terminate immediately" option... or am I missing the bigger picture. Thank you so much for writing.

      No. flock returns a false value if it cannot lock a file because it is already locked. The idea is that you then exit your program:

      use Fcntl qw(LOCK_EX LOCK_NB); my $scriptname = $0; # assuming that all script instances will be invo +ked the same way open my $script, $scriptname or die "Couldn't find myself?! Looked for '$script', but got $!"; if( !flock $script, LOCK_EX | LOCK_NB ) { print "We are already running\n"; exit 1; }; sleep 60