Python Unblocked Read File

I want to read a file with unlocked mode. So what I liked below

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!!"

But the value flagstill represents 0. Why ..? I think I should be changed in accordance withos.O_NONBLOCK

And of course, if I call fd.read (), it gets blocked when reading ().

+4
source share
1 answer

O_NONBLOCKis a status flag, not a descriptor flag. Therefore, use F_SETFLto set the status flags of the file , not F_SETFDwhat to indicate the flags of the file descriptor .

Also, be sure to pass the integer file descriptor as the first argument to fcntl.fcntl, not to the Python file file. So use

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!!
+7

All Articles