本文介绍了确保只有一个 Perl 程序实例正在运行的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有几种方法可以做到这一点,但我不确定哪一种是最好的.

There are several ways to do this, but I'm not sure which one of them is the best.

这是我能想到的:

  • 使用 pgrep 查找进程.
  • 使用 flock 将脚本自身锁定,然后在每次运行时检查它是否被锁定.
  • 在/var/run/program_name.pid 中创建一个 pid 文件并检查是否存在,并在需要时比较 pid.

可能有更多方法可以做到这一点.您认为最好的方法是什么?

There are probably more ways to do this. What do you think is the best approach?

推荐答案

有很多方法可以做到.PID 文件是执行此操作的传统方法.您还可以锁定文件,例如程序本身.这段代码就可以解决问题:

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";

与 PID 文件相比,一个优点是文件在程序退出时会自动解锁.以可靠的方式实施要容易得多.

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.

这篇关于确保只有一个 Perl 程序实例正在运行的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 10:09
查看更多