国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python進程通信之匿名管道實例講解

2020-02-23 00:40:09
字體:
來源:轉載
供稿:網友

匿名管道

管道是一個單向通道,有點類似共享內存緩存.管道有兩端,包括輸入端和輸出端.對于一個進程的而言,它只能看到管道一端,即要么是輸入端要么是輸出端.

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)

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 惠安县| 阿城市| 刚察县| 沁阳市| 寿阳县| 西吉县| 威信县| 淳安县| 林芝县| 永寿县| 泸西县| 巴林右旗| 赣榆县| 双鸭山市| 江安县| 左权县| 克拉玛依市| 肇庆市| 铁岭市| 应用必备| 河南省| 咸丰县| 昌宁县| 娱乐| 汉沽区| 雷山县| 东城区| 南和县| 南澳县| 大厂| 通州市| 金山区| 黑山县| 肇源县| 晋江市| 永定县| 黄平县| 陇南市| 淅川县| 阿坝| 阳江市|