如何从os.pipe()中读取而不被阻塞? [英] How to read from an os.pipe() without getting blocked?

查看:308
本文介绍了如何从os.pipe()中读取而不被阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从打开的os.pipe()中读取内容,以查看读取时是否为空.问题是,调用read()会使程序阻塞在那里,直到实际上有什么要读取的地方为止,但是如果我正在做的测试成功的话,就不会有任何内容.

I'm trying to read from an open os.pipe() to see if it's empty at the moment of the reading. The problem is that calling read() causes the program to block there until there is actually something to read there however there won't be any, if the test I'm doing succeeded.

我知道我可以在超时的情况下使用select.select(),但是我想知道是否还有其他解决方法.

I know I can use select.select() with a timeout however I wanted to know if there is another solution to the problem.

推荐答案

您可以尝试一下.

import os, fcntl
fcntl.fcntl(thePipe, fcntl.F_SETFL, os.O_NONBLOCK) 

使用此thePipe.read()应该是非阻塞的.

With this thePipe.read() should be non-blocking.

来自 pipe(7)手册页:

From pipe(7) man page:

如果进程尝试从 空管道,然后read(2)将阻塞 直到数据可用. (...) 通过使用,可以进行非阻塞I/O fcntl(2)F_SETFL操作 启用O_NONBLOCK打开文件状态 标记.

If a process attempts to read from an empty pipe, then read(2) will block until data is available. (...) Non-blocking I/O is possible by using the fcntl(2) F_SETFL operation to enable the O_NONBLOCK open file status flag.

这篇关于如何从os.pipe()中读取而不被阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆