DaemonRunner: Detecting if a daemon is already running

允我心安 提交于 2019-12-24 06:06:59

问题


I have a script using DaemonRunner to create a daemon process with a pid file. The problem is that if someone tried to start it without stopping the currently running process, it will silently fail. What's the best way to detect an existing process and alert the user to stop it first? Is it as easy as checking the pidfile?

My code is similar to this example:

#!/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()

To see my actual code, look at investor.py in: https://github.com/jgillick/LendingClubAutoInvestor


回答1:


since DaemonRunner handles its own lockfile, it's more wisely to refer to that one, to be sure you can't mess up. Maybe this block can help you with that:

Add
from lockfile import LockTimeout
to the beginning of the script and surround daemon_runner.doaction() like this

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



回答2:


This is the solution that I decided to use:

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()

Is this a best practice or is there a better way?



来源:https://stackoverflow.com/questions/16247002/daemonrunner-detecting-if-a-daemon-is-already-running

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!