我试图理解 select()
在 Unix 中如何作为一个函数工作。我有一个带套接字的工作示例,但在使用文件时遇到问题。在文件对象上使用 select()
时,它不会等待 - 而是直接继续执行后面的代码。
这个示例运行良好:
import socket
from select import select
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind(("127.0.0.1", 1111))
server_socket.listen(5)
# this function wait when server_socket descriptor will change
read, write, error = select([server_socket], [], [])
# this part print when I use "nc 127.0.0.1 1111"
print(server_socket)
但是当我尝试对文件使用相同的代码时,我得到了意想不到的结果。
import os
import fcntl
from select import select
file_descriptor = os.open('/tmp/test_file', os.O_CREAT)
# lock file? I try to use lockf, other options
fcntl.flock(file_descriptor, os.F_LOCK | os.O_SHLOCK)
# I think that select must wait when the file will be unlocked
read, write, error = select([], [file_descriptor], [])
# prints immediately
print(file_descriptor)
在 Unix 或像 osx 这样基于它的操作系统上,你应该使用管道。
来自 python 文档
Note that on Windows, it only works for sockets; on other operating systems, it also works for other file types (in particular, on Unix, it works on pipes). It cannot be used on regular files to determine whether a file has grown since it was last read.
我是一名优秀的程序员,十分优秀!