Skip to main content
 首页 » 编程设计

python之守护进程 : Detecting if a daemon is already running

2025年05月04日6虾米哥

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

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

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

请您参考如下方法:

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

添加
从锁文件导入 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