python管道pipe

1.什么是管道
Linux进程间通讯方式的一种,管道有两端,读端和写端。建立管道,而后从父进程fork出子进程,
父进程和子进程拥有共同的读写文件描述符,能够实现子进程写文件,父进程读文件的操做。
示意图以下:
python

2.具体操做
子进程关闭读端,父进程关闭写端,子进程负责写,父进程负责读。
代码示例以下:3d

import os, time, sys
pipe_name = 'pipe_test'

def child( ):
    pipeout = os.open(pipe_name, os.O_WRONLY)
    counter = 0
    while True:
        time.sleep(1)
        os.write(pipeout, 'Number %03d\n' % counter)
        counter = (counter+1) % 5

def parent( ):
    pipein = open(pipe_name, 'r')
    while True:
        line = pipein.readline()[:-1]
        print 'Parent %d got "%s" at %s' % (os.getpid(), line, time.time( ))

if not os.path.exists(pipe_name):
    os.mkfifo(pipe_name)  
pid = os.fork()    
if pid != 0:
    parent()
else:       
    child()

运行结果:
code

相关文章
相关标签/搜索