【问题标题】:DaemonRunner: Detecting if a daemon is already runningDaemonRunner:检测一个守护进程是否已经在运行
【发布时间】:2013-04-27 00:20:20
【问题描述】:

我有一个使用 DaemonRunner 的脚本来创建一个带有 pid 文件的守护进程。问题是,如果有人试图在不停止当前正在运行的进程的情况下启动它,它将默默地失败。检测现有进程并提醒用户先停止它的最佳方法是什么?查pidfile就这么简单吗?

我的代码和这个例子类似:

#!/usr/bin/python
import time
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/foo.pid'
        self.pidfile_timeout = 5
    def run(self):
        while True:
            print("Howdy!  Gig'em!  Whoop!")
            time.sleep(10)

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

要查看我的实际代码,请查看以下的investor.py: https://github.com/jgillick/LendingClubAutoInvestor

【问题讨论】:

    标签: python python-2.7 python-daemon


    【解决方案1】:

    由于 DaemonRunner 处理它自己的锁文件,因此更明智的做法是参考那个文件,以确保您不会搞砸。也许这个块可以帮助你:

    添加
    from lockfile import LockTimeout
    到脚本的开头并像这样包围daemon_runner.doaction()

    try:
        daemon_runner.do_action()
    except LockTimeout:
        print "Error: couldn't aquire lock"
        #you can exit here or try something else
    

    【讨论】:

    • 如果您需要可以缩短def __init__ 中的self.pidfile_timeout
    【解决方案2】:

    这是我决定使用的解决方案:

    lockfile = runner.make_pidlockfile('/tmp/myapp.pid', 1)
    if lockfile.is_locked():
        print 'It looks like a daemon is already running!'
        exit()
    
    app = App()
    daemon_runner = runner.DaemonRunner(app)
    daemon_runner.do_action()
    

    这是最佳做法还是有更好的方法?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      • 2014-07-03
      • 1970-01-01
      相关资源
      最近更新 更多