CPAN carries a module called File::Pid, that implements a PID file object that writes to a file. The documentation suggests it be used as:
use File::Pid;
my $pidfile = File::Pid->new({
file => '/some/file.pid',
});
$pidfile->write;
if ( my $num = $pidfile->running ) {
die "Already running: $num\n";
}
$pidfile->remove;
However, if you write()
before calling running()
, then the PID in the PID file gets overwritten with the current script’s PID, and thus running()
always returns the current scripts PID, and thus, if you run the example, it always bombs out.
Instead, you want to put the call to write()
after the call to running()
:
use File::Pid;
my $pidfile = File::Pid->new({file => '/some/file.pid', });
die "Already running in PID $num" if ( my $num = $pidfile->running );
$pidfile->write;
do_seomthing_useful();
$pidfile->remove;
Easy.