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
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值