确保只有一个 Perl 程序实例正在运行的最佳方法是什么?
有多种方法可以做到这一点,但我不确定哪一种是最好的。
我能想到的是:
- 使用pgrep查找进程。
- 让脚本使用flock来锁定自身,然后在每次运行时检查它是否被锁定。
- 在 /var/run/program_name.pid 中创建一个 pid 文件并检查是否存在,并在需要时比较 pid。
可能还有更多方法可以做到这一点。 您认为最好的方法是什么?
There are several ways to do this, but I'm not sure which one of them is the best.
Here's what I can think of:
- Look for the process using pgrep.
- Have the script lock itself using flock, and then check if it is locked each time it runs.
- Create a pid file in /var/run/program_name.pid and check for existence, and compare pids if needed.
There are probably more ways to do this. What do you think is the best approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
有很多方法可以做到这一点。 PID 文件是传统的方法。 您还可以锁定文件,例如程序本身。 这一小段代码就可以解决这个问题:
与 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:
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.