确保只有一个 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.
执行旧的 PID 文件技巧。
HTH
欢呼,
Rob
Do the old PID file trick.
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).