What's the best way to make sure only one instance of a Perl program is running?

怎甘沉沦 提交于 2019-11-28 18:43:34

There are many ways to do it. PID files are the traditional way to do it. You could also hold a lock on a file, for example the program itself. This small piece of code will do the trick:

use Fcntl ':flock';
open my $self, '<', $0 or die "Couldn't open self: $!";
flock $self, LOCK_EX | LOCK_NB or die "This script is already running";

One advantage over PID files is that files automatically get unlocked when the program exits. It's much easier to implement in a reliable way.

Do the old PID file trick.

  • start process
  • see if there is a file called "myprog.PID"
  • check for existence of running proc. with matching PID using kill 0, $pid
  • if prog name of PID proc. matches, complain loudly and exit
  • if not, clean up stale "myprog.PID"
  • create a file called "myprog.PID" and then continue

HTH

cheers,

Rob

All of the options that you list are fine. One thing with this though, is to be aware that in rare cases, you can end up with a process that runs for a very long time (i.e., stuck waiting on something). You might want to think about keeping an eye on how long the other running instance has been running and possibly send yourself an alert if it exceeds a certain amount of time (such as a day perhaps).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!