Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

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

by stevieb (Canon)
on Dec 02, 2022 at 16:41 UTC ( [id://11148502]=note: print w/replies, xml ) Need Help??

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

I wrote Script::Singleton exactly for this task.

It uses the shared memory functionality of IPC::Shareable which I also maintain.

To use it, you literally only need to use it:

use Script::Singleton;


It uses the script's path and filename as the "glue" aka. shared memory key for identification. If you want to use a custom glue:

use Script::Singleton glue => 'UNIQUE GLUE STRING';

Best part I like about it is that if there's a system interruption or reboot, you don't have to worry about lock files hanging around.

Here's an example (using the module with the warn parameter which is false by default):

use warnings; use strict; use Script::Singleton warn => 1; sleep 5;

Run the script in one CLI, and within five seconds, run it in a second window and you'll get:

Process ID 24891 exited due to exclusive shared memory collision at segment/semaphore key '0x40d7106c'

Log In?

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

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (2)
As of 2024-07-23 19:54 GMT
Find Nodes?
    Voting Booth?

    No recent polls found

    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.