The following module makes it easy to only let one copy of a program run at a time. At the top of your script add:
use My::ThereCanBeOnlyOne '/tmp/myprogram.pid';
You can also specify LockFile::Simple options to change the behavior as in:
use My::ThereCanBeOnlyOne '/tmp/myprogram.pid', -hold => 0, -stale => 1, -max => 1;
It is recommended you chose a lockfile outside of /tmp as that would allow a denial of service attack from another user on the same machine.
package My::ThereCanBeOnlyOne; use strict; use LockFile::Simple; my $Lock; sub import { my $self = shift; my $lockfile = shift || die "please provide lockfile"; my %args = @_; my $locker = LockFile::Simple->make(-autoclean => 0, %args); $Lock = $locker->lock($lockfile, '%f') and return 1; open(LOCKFILE, "< $lockfile") or die __PACKAGE__."Unable to open $lockfile: $!"; my $other_pid = <LOCKFILE>; close(LOCKFILE); chomp($other_pid); die __PACKAGE__.": $lockfile: $other_pid still running. $$ exiting\n +"; } END { $Lock->release(); } 1;

Replies are listed 'Best First'.
Re: Only let one copy of program run at a time
by Kanji (Parson) on Aug 20, 2003 at 13:29 UTC
Re: Only let one copy of program run at a time
by Mr. Muskrat (Canon) on Aug 20, 2003 at 13:32 UTC