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

相關文章
相關標籤/搜索