【问题标题】:python Non-block read filepython 非阻塞读取文件
【发布时间】:2015-05-11 16:03:47
【问题描述】:

我想以非阻塞模式读取文件。 所以我喜欢下面

import fcntl
import os

fd = open("./filename", "r")
flag = fcntl.fcntl(fd.fileno(), fcntl.F_GETFD)
fcntl.fcntl(fd, fcntl.F_SETFD, flag | os.O_NONBLOCK)
flag = fcntl.fcntl(fd, fcntl.F_GETFD)
if flag & os.O_NONBLOCK:
    print "O_NONBLOCK!!"

但是flag的值仍然代表0。 为什么..?我觉得应该改成os.O_NONBLOCK

当然,如果我调用 fd.read(),它会在 read() 处被阻塞。

【问题讨论】:

    标签: python python-2.7 nonblocking


    【解决方案1】:

    O_NONBLOCK 是状态标志,而不是描述符标志。因此使用F_SETFLset File status flags,而不是F_SETFD,这是setting File descriptor flags

    另外,请务必将整数文件描述符作为第一个参数传递给fcntl.fcntl,而不是 Python 文件对象。因此使用

    f = open("/tmp/out", "r")
    fd = f.fileno()
    fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
    

    而不是

    fd = open("/tmp/out", "r")
    ...
    fcntl.fcntl(fd, fcntl.F_SETFD, flag | os.O_NONBLOCK)
    flag = fcntl.fcntl(fd, fcntl.F_GETFD)
    

    import fcntl
    import os
    
    with open("/tmp/out", "r") as f:
        fd = f.fileno()
        flag = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)
        flag = fcntl.fcntl(fd, fcntl.F_GETFL)
        if flag & os.O_NONBLOCK:
            print "O_NONBLOCK!!"
    

    打印

    O_NONBLOCK!!
    

    【讨论】:

      猜你喜欢
      • 2017-02-18
      • 2016-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-17
      • 1970-01-01
      • 2015-05-05
      相关资源
      最近更新 更多