在python中实现生产者和消费者的例子(三):使用fork和pipe
2013-09-04 13:27
701 查看
本文介绍如何用os模块中的fork和pipe实现生产者和消费者的例子
import os
import time
total=0
r,w=os.pipe()
pid0=os.getpid()
print '主进程',pid0
pid1=os.fork()
#为了证明os.fork()有两个返回值
#print '测试',pid1
#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' ,pid1,'子进程1',os.getpid()
else :
status1=os.waitpid(pid1,0)
pid2=os.fork()
a=0
if pid2 == 0:
print 'this is child02' ,pid2,'子进程2',os.getpid()
os.close(r)
fw=os.fdopen(w,'w')
for i in range(100):
a=a+1
fw.write(str(a))
print a,' 01'
fw.close()
else :
#status2=os.waitpid(pid2,0)
print 'this is parent00','主进程',os.getpid(),' its child01',pid1,' its child02',pid2
os.close(w)
fr=os.fdopen(r,'r')
print fr.read(),' 02'
fr.close()
import os
import time
total=0
r,w=os.pipe()
pid0=os.getpid()
print '主进程',pid0
pid1=os.fork()
#为了证明os.fork()有两个返回值
#print '测试',pid1
#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' ,pid1,'子进程1',os.getpid()
else :
status1=os.waitpid(pid1,0)
pid2=os.fork()
a=0
if pid2 == 0:
print 'this is child02' ,pid2,'子进程2',os.getpid()
os.close(r)
fw=os.fdopen(w,'w')
for i in range(100):
a=a+1
fw.write(str(a))
print a,' 01'
fw.close()
else :
#status2=os.waitpid(pid2,0)
print 'this is parent00','主进程',os.getpid(),' its child01',pid1,' its child02',pid2
os.close(w)
fr=os.fdopen(r,'r')
print fr.read(),' 02'
fr.close()
相关文章推荐
- 在python中实现生产者和消费者的例子(一):使用multiprocessing和pipe()
- 在python中实现生产者和消费者的例子(五):使用threading模块和全局变量
- 在python中实现生产者和消费者的例子(二):使用multiprocessing和queue
- 在python中实现生产者和消费者的例子(四):使用thread模块和全局变量
- python使用threading.condition实现生产者消费者
- 使用Python实现生产者消费者问题
- 使用Python实现生产者消费者问题
- python使用队列实现生产者消费者
- python使用queue队列实现生产者消费者
- python中线程的使用以及生产者和消费者的实现
- 《Lua程序设计》9.2 管道(pipe)与过滤器(filter) 包含使用协同函数实现“生产者——消费者”问题的实例代码
- linux 线程间使用信号量实现消费者生产者
- 11.python并发入门(part8 基于线程队列实现生产者消费者模型)
- python使用fork实现守护进程的方法
- python中使用pyhook实现键盘监控的例子
- 使用swoole实现生产者消费者模型(2)
- 4.利用python生成器实现简单的“生产者消费者”模型
- 使用Java的BlockingQueue实现生产者-消费者
- How to: 使用 数据流 实现生产者-消费者模式
- 使用BlockingQueue实现生产者和消费者模式