Skip to main content
 首页 » 编程设计

Python 守护进程 : checking to have one daemon run at all times

2024年10月25日13think

我的警报.py

from daemon import Daemon 
import os, time, sys 
 
class alertDaemon(Daemon): 
    def run(self): 
        while True: 
            time.sleep(1) 
 
if __name__ == "__main__": 
    alert_pid = '/tmp/ex.pid' 
 
    # if pid doesnt exists run 
    if os.path.isfile(alert_pid):            # is this check enough? 
        sys.exit(0) 
 
    daemon = alertDaemon(alert_pid) 
    daemon.start() 

鉴于没有其他程序或用户会创建 pid 文件:

1) 是否存在pid不存在守护进程还在运行的情况?
2) 是否存在 pid 存在但守护进程未运行的情况?

因为如果至少对上述问题之一的回答是肯定的,那么如果我的目标是让一个守护进程始终运行,那么仅仅检查 pid 文件是否存在是不够的。

问:如果我必须检查进程,我希望避免像系统调用 ps -ef 和 grep 之类的脚本名称。有执行此操作的标准方法吗?

注意:脚本 myalert.py 将是一个 cronjob

请您参考如下方法:

python-daemon库,它是 PEP 3143 的引用实现:“标准守护进程库”,通过在传递给 DaemonContext 对象的 pid 文件上使用文件锁(通过 lockfile 库)来处理此问题。底层操作系统保证在守护进程退出时释放文件锁,即使它是不干净地退出的。这是一个简单的用法示例:

import daemon 
from daemon.pidfile import PIDLockFile 
 
context = daemon.DaemonContext( 
    pidfile= PIDLockFile('/var/run/spam.pid'), 
    ) 
 
with context: 
    main() 

因此,如果一个新实例启动,它不必确定创建现有 pid 文件的进程是否仍在通过 pid 本身运行;如果它可以获得文件锁,则没有其他实例正在运行(因为它们已经获得了锁)。如果它无法获取锁,则必须运行另一个守护进程实例。

您遇到麻烦的唯一方法是有人在守护程序运行时出现并手动删除了 pid 文件。但我认为您不必担心有人故意以这种方式破坏东西。

理想情况下,python-daemon 将成为标准库的一部分,这也是 PEP 3143 的最初目标。不幸的是,PEP 被推迟了,主要是因为没有人愿意真正去做加入标准库所需的剩余工作:

Further exploration of the concepts covered in this PEP has been deferred for lack of a current champion interested in promoting the goals of the PEP and collecting and incorporating feedback, and with sufficient available time to do so effectively.