`

python 信号处理僵尸进程

 
阅读更多

#! coding=utf-8

 

#使用信号解决zombie问题

 

import os, time, signal

 

 

 

def chldhandler(signum ,stackframe):

 

    while 1:

        try:

            result = os.waitpid(-1, os.WNOHANG)

 

        except:

            print '.............'

            break

    signal.signal(signal.SIGCHLD, chldhandler)

 

#每次收到SIGCHLD信号,就调用chldhandler这个处理函数

signal.signal(signal.SIGCHLD, chldhandler)

 

 

 

print "Before the fork ,my pid is ",os.getpid()

 

pid =os.fork()

 

if pid:

    print "hello from the parent ,the child will be pid %d" %pid

    print "in parent ,start time at %s"%(time.time())

    time.sleep(10)

    print "in parent ,end time at %s"%(time.time())

 

 

else:

    """

    5s 之后 子进程死掉,然后chldhandler处理僵尸进程

    """

    print "in child ,sart time at %s"%(time.time())

    time.sleep(5)

    print "in child ,end time at %s"%(time.time())

 

 

输出:

Before the fork ,my pid is  29566

in child ,sart time at 1375251988.9

hello from the parent ,the child will be pid 29567

in parent ,start time at 1375251988.9

in child ,end time at 1375251993.9

.............

in parent ,end time at 1375251993.9

 

五秒钟之后,子进程结束,父进程收到信号开始处理僵尸进程,发现其实父进程没有sleep 10秒,这是因为

sleep()有一个特殊的情况,如果任意一个信号处理程序被调用,睡眠会被立刻终止,而不是继续等待剩余的时间。

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics