Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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

by Corion (Patriarch)
on Dec 02, 2022 at 16:43 UTC ( [id://11148503]=note: print w/replies, xml ) Need Help??


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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2024-04-16 08:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found