匿名管道
管道是一個單向通道,有點類似共享內存緩存.管道有兩端,包括輸入端和輸出端.對于一個進程的而言,它只能看到管道一端,即要么是輸入端要么是輸出端.
os.pipe()返回2個文件描述符(r, w),表示可讀的和可寫的.示例代碼如下:
代碼如下:
#!/usr/bin/python
import time
import os
def child(wpipe):
print('hello from child', os.getpid())
while True:
msg = 'how are you/n'.encode()
os.write(wpipe, msg)
time.sleep(1)
def parent():
rpipe, wpipe = os.pipe()
pid = os.fork()
if pid == 0:
child(wpipe)
assert False, 'fork child process error!'
else:
os.close(wpipe)
print('hello from parent', os.getpid(), pid)
fobj = os.fdopen(rpipe, 'r')
while True:
recv = os.read(rpipe, 32)
print recv
parent()
輸出如下:
代碼如下:
('hello from parent', 5053, 5054)
('hello from child', 5054)
how are you
how are you
how are you
how are you
我們也可以改進代碼,不用os.read()從管道中讀取二進制字節,而是從文件對象中讀取字符串.這時需要用到os.fdopen()把底層的文件描述符(管道)包裝成文件對象,然后再用文件對象中的readline()方法讀取.這里請注意文件對象的readline()方法總是讀取有換行符'/n'的一行,而且連換行符也讀取出來.還有一點要改進的地方是,把父進程和子進程的管道中不用的一端關閉掉.
代碼如下:
#!/usr/bin/python
import time
import os
def child(wpipe):
print('hello from child', os.getpid())
while True:
msg = 'how are you/n'.encode()
os.write(wpipe, msg)
time.sleep(1)
def parent():
rpipe, wpipe = os.pipe()
pid = os.fork()
if pid == 0:
os.close(rpipe)
child(wpipe)
assert False, 'fork child process error!'
else:
os.close(wpipe)
新聞熱點
疑難解答