On Dec 9, 11:43 am, ron.egg...@gmail.com (Cerr) wrote:
> Hi There,
>
> I use below code to make sure i have only one instance of my script
> running at a time. But weirdly enough i sometimes seem to have running
> two instances. This script is getting called on a regular basis by a
> cron job and may take a long time (30+min)to complete but still...I
> can't figure out what would be wrong with this code, anyone?
>
> #[PID]
>   #Check if PID file already exists
>   if ( -s $PIDloc){
>     print "THERE IS ALREADY AN INSTANCE OF UPDATESERVER RUNNING\n
> check \"".$PIDloc."\"\n";
>     syslog('info',"THERE IS ALREADY AN INSTANCE OF UPDATESERVER RUNNING
> \n check \"".$PIDloc."\"");
>     exit(999);
>   }
>   #if it doesn't exist, create it (gets ereased atr the bottom of MAIN
> on completion)
>   my $pid = $$;

There's a tiny race condition  at this point since  the pidfile still
hasn't been created.  What if another cron fires off during this
very short window, doesn't see the pidfile, then slips through...
Or, maybe even the shorter window between pidfile creation
and its content being written  is the problem. Perhaps an
atomic 'flock' on the pidfile would be a good idea to eliminate
the latter window...


>   open my $fd,'>', $PIDloc or die $!;

Since this is a cron,  wouldn't an open failure remain under the
radar  unless syslog'ed?  Admittedly, I don't know why or how
that would happen but you might as well have the security
camera running just in case...

>   print $fd $pid;

Not to get too crazy but "print's" can fail too (of course rarely),
but, leaving no pebble unturned, you might want to do this:

print $fd $pid or syslog 'info', "print failure: ....", );

>   close $fd or die $!;

Same here.  syslog rather than 'die' here too since, if the
'close' were to fail,  the buffer might may not  get flushed
and the file'd remain empty.

--
Charles DeRykus


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to