perl’s File::PID trickiness

I have a program that uses perl’s File::PID but I was having some issue where the program would occasionally start multiple times.

Finally today I spent some time to figure out what’s going on. It seems that if you use the '$pidfile->write' function after checking whether it’s running already with '$pidfile->running()' then it puts back NOT the PID of the currently running process, but the PID that was there before!

Unless I’m misunderstanding my test result, you (I) need to do this to get the new PID into the old pidfile:


use File::Pid;
my $pidfile = File::Pid->new({
file => '/var/run/upload_cdn.pid',
});

my $num = $pidfile->running();

if ( $num ){

die "already running: $num\n\n";

} else {

$pidfile->remove;

my $pidfile2 = File::Pid->new({
file => '/var/run/upload_cdn.pid',
});

my $pid = $pidfile2->write;

if( $pid ){
&_log("Now running with PID $pid\n");
}

}

#$pidfile->write; ## This was putting the original non-running PID back into the file

Maybe I was doing something wrong or maybe there’s a better way to handle this? Hopefully my program won’t start running multiple times any more!

This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to perl’s File::PID trickiness

  1. Frédéric BLOISE says:

    Hi,

    It seems to me there’s a better way :

    use File::Pid;
    my $pidfile = File::Pid->new( { file => ‘/var/run/upload_cdn.pid’, pid => $$ } );

    my $num = $pidfile->running();

    if ($num) {
    die “already running: $num\n\n”;
    }
    $pidfile->write;

    $pidfile->remove;

    • admin says:

      Thanks for your comment, Frédéric!

      “This constructor takes two optional paramters. (typo from CPAN)
      file
      pid – The pid to write to a new pidfile. If not specified, $$ is used when the pid file doesn’t exist. When the pid file does exist, the pid inside it is used.”

      I will give this method a try.

Leave a Reply

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