我是靠谱客的博主 雪白白羊,这篇文章主要介绍python 管道阻塞,现在分享给大家,希望可以做个参考。

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

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/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,官网中给出了介绍

复制代码
1
2
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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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

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

复制代码
1
2
3
4
5
6
7
8
hellohellohellohello hellohellohellohello hellohellohellohello hellohellohellohello hellohellohellohello hellohellohellohello hellohellohellohello hellohellohellohello

最后

以上就是雪白白羊最近收集整理的关于python 管道阻塞的全部内容,更多相关python内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部