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.

  • 相关阅读:
    Scala刮:使用Intellij IDEA写hello world
    翻译器DIY它———算在英文文本中的单词数,字符和行数
    ZOJ3605-Find the Marble(可能性DP)
    我不需要你喜欢我
    thinkphp5的auth权限认证(转自thinkphp官方文档+自己总结)
    程序员中一些老的程序员去哪了
    信息学竞赛学习资料整理
    m_Orchestrate learning system---二十九、什么情况下用数据库做配置字段,什么情况下用配置文件做配置
    按键精灵使用心得
    thinkphp5中的配置如何使用
  • 原文地址:https://www.cnblogs.com/jkklearn/p/13667285.html
Copyright © 2011-2022 走看看