zoukankan      html  css  js  c++  java
  • python 守护进程daemon

    import time
    import os
    import sys
    def close_std_fd():
        f = open(os.devnull, 'w')
        sys.stdin = f
        sys.stdout = f
        sys.stderr = f
    
    def daemon(func):
        pid = os.fork()
        if pid > 0:
            return
        os.setsid()
        pid = os.fork()
        if pid > 0:
            return
        os.chdir('/')
        os.umask(0)
        close_std_fd()
        func()
    
    
    def maketest():
            time.sleep(8888)
    
    daemon(maketest)
    # -*-coding:utf-8-*-
    import sys, os
    
    '''将当前进程fork为一个守护进程
    
        注意:如果你的守护进程是由inetd启动的,不要这样做!inetd完成了
        所有需要做的事情,包括重定向标准文件描述符,需要做的事情只有
        chdir() 和 umask()了
    '''
    def daemonize(stdin='/dev/null',stdout= '/dev/null', stderr= 'dev/null'):
        '''Fork当前进程为守护进程,重定向标准文件描述符
            (默认情况下定向到/dev/null)
        '''
        #Perform first fork.
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)  #first parent out
        except OSError, e:
            sys.stderr.write("fork #1 failed: (%d) %s
    " %(e.errno, e.strerror))
            sys.exit(1)
    
        #从母体环境脱离
        os.chdir("/")
        os.umask(0)
        os.setsid()
        #执行第二次fork
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0) #second parent out
        except OSError, e:
            sys.stderr.write("fork #2 failed: (%d) %s]n" %(e.errno,e.strerror))
            sys.exit(1)
    
        #进程已经是守护进程了,重定向标准文件描述符
        for f in sys.stdout, sys.stderr: f.flush()
        si = file(stdin, 'r')
        so = file(stdout,'a+')
        se = file(stderr,'a+',0)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())
    
    def _example_main():
        '''示例函数:每秒打印一个数字和时间戳'''
        import time
        sys.stdout.write('Daemon started with pid %d
    ' % os.getpid())
        sys.stdout.write('Daemon stdout output
    ')
        sys.stderr.write('Daemon stderr output
    ')
    
        c = 0
        while True:
            sys.stdout.write('%d: %s
    ' %(c, time.ctime()))
            sys.stdout.flush()
            c = c+1
            time.sleep(1)
    
    if __name__ == "__main__":
        daemonize('/dev/null','/home/del/daemon.log','home/del/daemon.log')
        _example_main()

    linux 中生成一个守护进程 为什么要 fork 两次。

    All right, so now first of all: what is a zombie process?

    It's a process that is dead, but its parent was busy doing some other work, hence it could not collect the child's exit status.

    In some cases, the child runs for a very long time, the parent cannot wait for that long, and will continue with it's work (note that the parent doesn't die, but continues its remaining tasks but doesn't care about the child).

    In this way, a zombie process is created.


    Now let's get down to business. How does forking twice help here?

    The important thing to note is that the grandchild does the work which the parent process wants its child to do.

    Now the first time fork is called, the first child simply forks again and exits. This way, the parent doesn't have to wait for a long time to collect the child's exit status (since the child's only job is to create another child and exit). So, the first child doesn't become a zombie.

    As for the grandchild, its parent has already died. Hence the grandchild will be adopted by the init process, which always collects the exit status of all its child processes. So, now the parent doesn't have to wait for very long, and no zombie process will be created.

  • 相关阅读:
    CentOS 7.X 关闭SELinux
    删除或重命名文件夹和文件的方法
    centos7-每天定时备份 mysql数据库
    centos7 tar.gz zip 解压命令
    MySQL5.6/5.7/8.0版本授权用户远程连接
    下载CentOS7系统
    使用js实现tab页签切换效果
    sql优化常用的几种方法
    mysql 多表联查的快速查询(索引)
    【图论】强连通分量+tarjan算法
  • 原文地址:https://www.cnblogs.com/jkklearn/p/13667285.html
Copyright © 2011-2022 走看看