python 管道阻塞

我使用os.pipe 写管道按照菜鸟教程的写的,发现巨坑无比,菜鸟教程的写法:

网址:http://www.runoob.com/python/os-pipe.html

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

print "The child will write text to a pipe and "
print "the parent will read the text written by child..."

# file descriptors r, w for reading and writing
r, w = os.pipe() 

processid = os.fork()
if processid:
    # This is the parent process 
    # Closes file descriptor w
    os.close(w)
    r = os.fdopen(r)
    print "Parent reading"
    str = r.read()
    print "text =", str   
    sys.exit(0)
else:
    # This is the child process
    os.close(r)
    w = os.fdopen(w, 'w')
    print "Child writing"
    w.write("Text written by child...")
    w.close()
    print "Child closing"
    sys.exit(0)

这套代码表面看上去没什么问题,跑起来也没有问题,但是你加入改造必然出现问题,这个问题就是会出现阻塞,如果你用轮询str = r.read()和 w.write("Text written by child...")那么必然出现问题你会发现读的一端卡住了,读不到内容了,然后我使用了poll,selector 还是不行因为返回的event总是32而不是select.POLLIN,这是邪门了,我去读python手册返回的是我去读python的手册读到了os.read和os.write,官网中给出了介绍

Read at most n bytes from file descriptor fd. Return a bytestring containing the bytes read. If the end of the file referred to by fd has been reached, an empty bytes object is returned.

最后如此写代码就可以解决阻塞问题,用最原始的os.write和os.read

import os, time,select

r,w = os.pipe()
pid = os.fork()

if pid == 0:
    print "begin write"
    os.close(r)
    while 1:
        os.write(w,"hello")
        pass
    pass
else:
    print "begin_read"
    os.close(w)
    while 1:
        str = os.read(r,20)
        if(str):
            print str
        pass

    pass

你会发现问题得到解决不停的输出:

hellohellohellohello
hellohellohellohello
hellohellohellohello
hellohellohellohello
hellohellohellohello
hellohellohellohello
hellohellohellohello
hellohellohellohello

猜你喜欢

转载自blog.csdn.net/qq_32783703/article/details/80184180