zoukankan      html  css  js  c++  java
  • 如何使用python书写守护进程?daemon、python-daemon

    
    

    可以参考的supervisor实现:https://github.com/Supervisor/supervisor;http://supervisord.org/configuration.html

    
    

    pip包python-daemon:https://www.jianshu.com/p/76ecdea99ac7;https://www.python.org/dev/peps/pep-3143/;https://github.com/serverdensity/python-daemon

    
    

    https://pypi.org/project/python-daemon/

    
    

    来个摘抄的示例:https://codeday.me/bug/20180115/119802.html





    #
    !/usr/bin/env python3.5 import sys import os import time import argparse import logging import daemon from daemon import pidfile debug_p = False def do_something(logf): ### This does the "work" of the daemon logger = logging.getLogger('eg_daemon') logger.setLevel(logging.INFO) fh = logging.FileHandler(logf) fh.setLevel(logging.INFO) formatstr = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' formatter = logging.Formatter(formatstr) fh.setFormatter(formatter) logger.addHandler(fh) while True: logger.debug("this is a DEBUG message") logger.info("this is an INFO message") logger.error("this is an ERROR message") time.sleep(5) def start_daemon(pidf, logf): ### This launches the daemon in its context ### XXX pidfile is a context with daemon.DaemonContext( working_directory='/var/lib/eg_daemon', umask=0o002, pidfile=pidfile.TimeoutPIDLockFile(pidf), ) as context: do_something(logf) if __name__ == "__main__": parser = argparse.ArgumentParser(description="Example daemon in Python") parser.add_argument('-p', '--pid-file', default='/var/run/eg_daemon.pid') parser.add_argument('-l', '--log-file', default='/var/log/eg_daemon.log') args = parser.parse_args() start_daemon(pidf=args.pid_file, logf=args.log_file)

    和相应的脚本:

    #!/bin/bash
    #
    # eg_daemon      Startup script for eg_daemon
    #
    # chkconfig: - 87 12
    # description: eg_daemon is a dummy Python-based daemon
    # config: /etc/eg_daemon/eg_daemon.conf
    # config: /etc/sysconfig/eg_daemon
    # pidfile: /var/run/eg_daemon.pid
    #
    ### BEGIN INIT INFO
    # Provides: eg_daemon
    # Required-Start: $local_fs
    # Required-Stop: $local_fs
    # Short-Description: start and stop eg_daemon server
    # Description: eg_daemon is a dummy Python-based daemon
    ### END INIT INFO
    
    # Source function library.
    . /etc/rc.d/init.d/functions
    
    if [ -f /etc/sysconfig/eg_daemon ]; then
            . /etc/sysconfig/eg_daemon
    fi
    
    eg_daemon=/var/lib/eg_daemon/eg_daemon.py
    prog=eg_daemon
    pidfile=${PIDFILE-/var/run/eg_daemon.pid}
    logfile=${LOGFILE-/var/log/eg_daemon.log}
    RETVAL=0
    
    OPTIONS=""
    
    start() {
            echo -n $"Starting $prog: "
    
            if [[ -f ${pidfile} ]] ; then
                pid=$( cat $pidfile  )
                isrunning=$( ps -elf | grep  $pid | grep $prog | grep -v grep )
    
                if [[ -n ${isrunning} ]] ; then
                    echo $"$prog already running"
                    return 0
                fi
            fi
            $eg_daemon -p $pidfile -l $logfile $OPTIONS
            RETVAL=$?
            [ $RETVAL = 0 ] && success || failure
            echo
            return $RETVAL
    }
    
    stop() {
        if [[ -f ${pidfile} ]] ; then
            pid=$( cat $pidfile )
            isrunning=$( ps -elf | grep $pid | grep $prog | grep -v grep | awk '{print $4}' )
    
            if [[ ${isrunning} -eq ${pid} ]] ; then
                echo -n $"Stopping $prog: "
                kill $pid
            else
                echo -n $"Stopping $prog: "
                success
            fi
            RETVAL=$?
        fi
        echo
        return $RETVAL
    }
    
    reload() {
        echo -n $"Reloading $prog: "
        echo
    }
    
    # See how we were called.
    case "$1" in
      start)
        start
        ;;
      stop)
        stop
        ;;
      status)
        status -p $pidfile $eg_daemon
        RETVAL=$?
        ;;
      restart)
        stop
        start
        ;;
      force-reload|reload)
        reload
        ;;
      *)
        echo $"Usage: $prog {start|stop|restart|force-reload|reload|status}"
        RETVAL=2
    esac
    
    exit $RETVAL

    参考:

    http://blog.csdn.net/mjhmjhmjh123/article/details/22954831

    https://blog.csdn.net/zhaihaifei/article/details/70213431

    https://www.jianshu.com/p/76ecdea99ac7

  • 相关阅读:
    【视频开发】【电子电路技术】监控球机PTZ的功能介绍
    【电子电路技术】PoE供电技术的优缺点
    【电子电路技术】PoE供电技术的优缺点
    【python开发】利用PIP3的时候出现的问题Fatal error in launcher: Unable to create process using '"'
    【python开发】利用PIP3的时候出现的问题Fatal error in launcher: Unable to create process using '"'
    【Python开发】C和Python之间的接口实现
    Nginx配置域名转发实例
    Nginx配置域名跳转实例
    MySQL查看数据库大小、表大小和最后修改时间
    iptables阻止服务器被攻击
  • 原文地址:https://www.cnblogs.com/shengulong/p/8327942.html
Copyright © 2011-2022 走看看