Run only one copy of Perl script

Let’s suppose you need to have only one copy of your Perl script running. An elegant and short way to do that is a lock the script by itself. Add this code at the begginig of your script and it’ll avoid to run more than one copy.

use Fcntl ':flock';
open SELF, "< $0" or exit(1); flock SELF, LOCK_EX | LOCK_NB or exit(0);

2 responses to “Run only one copy of Perl script”

  1. What happens if your script dies (or the whole machine goes down) before it can unlock itself? 🙂

  2. I didn’t face this problem during 3 years of practical using this approach for all Billing background jobs. I suppose the system will release lock automatically if the script will die by some reason. Because flock operates with opened file handler and it will be close automatically.
    But of cource you can use signals to unlock the script:

    $SIG{__DIE__} = sub { flock SELF, LOCK_UN; }

    In my mind it’s not necessary.

Leave a Reply

Your email address will not be published. Required fields are marked *