2013-04-27 56 views
2

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

我的代码是类似这样的例子:

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

回答

0

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

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

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

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 
+0

如果需要,你可以缩短在'self.pidfile_timeout' 'def __init__' – ExploWare 2014-03-10 14:27:19

+0

这对我来说非常好。谢谢 – jnichols959 2015-01-21 22:53:01

相关问题