[英]Single instance of a python daemon (with python-daemon)
I want to create a program that runs forever, which there is only one instance running at a time and that can be launched with an init.d script. 我想创建一个永远运行的程序,一次只能运行一个实例,并且可以使用init.d脚本启动该程序。 python-daemon seems to be a good choice to do that as it is the reference implementation of PEP 3143 . python-daemon似乎是一个不错的选择,因为它是PEP 3143的参考实现。
Anyway I can't understand what the PID lock file is for, since it doesn't prevent the program to be run twice. 无论如何,我无法理解PID锁定文件的用途,因为它不会阻止程序运行两次。
Should I manually check for the existence of the lock file in my init.d script (based on '/etc/init.d/skeleton') ? 是否应该在init.d脚本(基于'/etc/init.d/skeleton')中手动检查锁定文件的存在? Also how am I supposed to kill it ? 另外我该怎么杀呢? Get the PID number in the PID file and send a SIGTERM ? 在PID文件中获取PID号并发送SIGTERM?
Thanks a lot. 非常感谢。
For me it effectively prevents via the PID file that a second instance is started. 对我来说,它可以有效地防止通过PID文件启动第二个实例。 Are you using it correctly? 您使用正确吗? My example is based on what I found at the PEP 3143 reference and in the sources: 我的示例基于在PEP 3143参考资料和来源中找到的内容:
#!/usr/bin/env python
import daemon, os, time, lockfile
with daemon.DaemonContext(
pidfile=lockfile.FileLock('./pydaemon.pid'),
working_directory=os.getcwd()):
for i in range(10):
with open('./daemon.log', 'a') as logFile:
logFile.write('%s %s\n' % (os.getpid(), i))
time.sleep(1)
If I start that once, it creates the PID lock file. 如果我启动一次,它将创建PID锁定文件。 If I start it a second time, the second instance sleeps until the first is finished; 如果我第二次启动它,那么第二个实例将一直休眠直到第一个实例完成为止; normal daemons won't finish, so this effectively blocks the second instance for good. 正常的守护程序不会完成,因此这将有效地永久阻止第二个实例。 If, however, the first daemon terminates, the second is started. 但是,如果第一个守护程序终止,则启动第二个守护程序。
I ended up using Sander Marechal's code whose site is currently down so here's the link to a pastebin : http://pastebin.com/FWBUfry5 我最终使用了Sander Marechal的代码,该代码的站点当前已关闭,所以这里是pastebin的链接: http : //pastebin.com/FWBUfry5
Below you can find an example of how you can use it, it produce the behavior I expected : it does not allow you to start two instances. 在下面,您可以找到一个如何使用它的示例,它产生了预期的行为:它不允许您启动两个实例。
import sys, time
from daemon import Daemon
class MyDaemon(Daemon):
def run(self):
while True:
time.sleep(1)
if __name__ == "__main__":
daemon = MyDaemon('/tmp/daemon-example.pid')
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
elif 'restart' == sys.argv[1]:
daemon.restart()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.