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

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值