您的位置:首页 > 编程语言 > Python开发

使用python的os.fork()为一个主进程生成多个子进程

2013-08-28 22:28 573 查看
先熟悉一下基础:

语句pid=os.fork(),会为当前进程产生一个子进程并返回两个值,为父进程返回子进程的进程ID,为子进程返回0。

语句r,w=os.pipe(),将创建一个读写的单向管道,用于多进程通信。

语句os.getpid和os.getppid,分别返回当前进程的ID和其父进程的ID。

对于初学者(包括本人),经常连续使用os.fork()语句,这样会为前面使用os.fork()产生的子进程也生成子进程。

下面将给出一个只为一个主进程生成多个子进程的方法(本文选择为主进程生成两个子进程),并将进程间等待与通信融入其中。

import os

total=0

r1,w1=os.pipe()

r2,w2=os.pipe()

pid0=os.getpid()

print '主进程',pid0

pid1=os.fork()

'''

print '测试',pid1 #为了演示os.fork()有两个返回值

#下面为了演示os.getpid()值不是固定的 其显示当前进程ID

if pid1==0:

print '子进程 ',pid1,os.getpid(),os.getppid()

else:

print '主进程 ',pid1,os.getpid(),os.getppid()

'''

if pid1 == 0:

print 'this is child01' ,'子进程1',os.getpid()

os.close(r1)

fw01=os.fdopen(w1,'w')

fw01.write('99')

else :

status1=os.waitpid(pid1,0)

pid2=os.fork()

if pid2 == 0:

print 'this is child02' ,'子进程2',os.getpid()

os.close(r2)

fw02=os.fdopen(w2,'w')

fw02.write('100')

else :

status2=os.waitpid(pid2,0)

print 'this is parent00','主进程',os.getpid(),' its child01',pid1,' its child02',pid2

os.close(w1)

os.close(w2)

fr001=os.fdopen(r1,'r')

fr002=os.fdopen(r2,'r')

add1=fr001.read()

add2=fr002.read()

total=total+int(add2)-int(add1)

print 'total =',total

代码中注释部分为了演示os.fork()和os.getpid()的返回值。大家可以发现在根据pid判断其为主进程后再次使用了os.fork()为其生成第二个子进程

其运行结果如下:

主进程 3564

this is child01 子进程1 3565

this is child02 子进程2 3566

this is parent00 主进程 3564 its child01 3565 its child02 3566

total = 1

可见为主进程3564生成两个子进程3565和3566
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: