python管道pipe

1.什么是管道
Linux进程间通信方式的一种,管道有两端,读端和写端。创建管道,然后从父进程fork出子进程,
父进程和子进程拥有共同的读写文件描述符,可以实现子进程写文件,父进程读文件的操作。
示意图如下:

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

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
' % 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()

运行结果:

原文地址:https://www.cnblogs.com/shijingjing07/p/7899611.html