python中os.waitpid() 注意:windows操作系统中os模块中没有os.fork() 函数
一下代码为os.waitpid()用法的演示。
该程序的3个示范输出再次证明了一部并发进程不可预测的本质
- import os
- import sys
- import time
- try :
- forkPID1 = os.fork()
- except OSError : # 如果操作系统不能创建进程,osfork()将会发出一个OSError异常
- sys.exit('Unable to create first child.')
- if forkPID1 != 0 :
- try :
- forkPID2 = os.fork()
- except OSError :
- sys.exit('Unable to create first child.')
- if forkPID2 > 0 :
- print 'Parent waiting for child precesses ...\n' + \
- '\t tpid : %d , forkPID1 : %d , forkPID2 : %d' \
- % ( os.getpid() , forkPID1 , forkPID2)
- try :
- child2 = os.waitpid (forkPID2 , 0)[0]
- except OSError :
- sys.exit("No child process with pid %d." %(forkPID2) )
- print 'Parent Child %d finished.' % child2
- elif forkPID2 == 0 :
- print 'Chile2 sleeping fot 4 seconds ....\n' + \
- '\tpid : %d , forkPID1: %d , forkPID2: %d' \
- % (os.getpid() , forkPID1 , forkPID2 )
- time.sleep(4) #规定进程保持的休眠时间 , 以秒为单位
- elif forkPID1 == 0 :
- print 'Child1 sleeping for 2 seconds ....\n' + \
- '\tpid : %d , forkPID1: %d' \
- % (os.getpid() , forkPID1)
- time.sleep(2)
- 3个示范输出:
- Parent waiting for child precesses ...
- tpid : 2468 , forkPID1 : 2469 , forkPID2 : 2470
- Child1 sleeping for 2 seconds ....
- pid : 2469 , forkPID1: 0
- Chile2 sleeping fot 4 seconds ....
- pid : 2470 , forkPID1: 2469 , forkPID2: 0
- Parent Child 2470 finished.
- Parent waiting for child precesses ...
- tpid : 2465 , forkPID1 : 2466 , forkPID2 : 2467
- Child1 sleeping for 2 seconds ....
- Chile2 sleeping fot 4 seconds ....
- pid : 2466 , forkPID1: 0
- pid : 2467 , forkPID1: 2466 , forkPID2: 0
- Parent Child 2467 finished.
- Parent waiting for child precesses ...
- tpid : 2634 , forkPID1 : 2635 , forkPID2 : 2636
- Child1 sleeping for 2 seconds ....
- pid : 2635 , forkPID1: 0
- Chile2 sleeping fot 4 seconds ....
- pid : 2636 , forkPID1: 2635 , forkPID2: 0
- Parent Child 2636 finished.
阅读(11615) | 评论(0) | 转发(0) |