导航

python守护进程

Posted on 2018-01-05 14:38  困或  阅读(466)  评论(0编辑  收藏  举报

1.守护进程

  [1]使用runner这个模块直接创建守护进程,非常方便。

  [2]运行方法:python xxx.py start|stop|restart

  [3]调用python xxx.py stop时,会给进程发送signal.SIGTERM信号,所以可以捕获此信号进行程序退出前的处理。

  [4]流程:

    1)调用python xxx.py start启动一个守护进程,例如进程号是1000。

    2)调用python xxx.py stop时,会给进程1000发送一个signal.SIGTERM信号,进程1000结束。

# -*- coding: utf-8 -*-
import os,sys,time
import threading
import signal
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/null'
        self.stderr_path = '/dev/null'
        self.pidfile_path = '/tmp/test.pid'
        self.pidfile_timeout = 5
        
    def run(self):
        #在这里添加主流程

        while True:
            time.sleep(10)
    
if __name__ == "__main__":
    app = App()
    daemon_runner = runner.DaemonRunner(app)
    daemon_runner.do_action()