尝试打开命名管道进行读取时 Python 代码挂起

标签 python file-io named-pipes nonblocking fifo

<分区>

我正在尝试使用命名管道在守护进程和客户端之间建立双向通信。代码在尝试打开用于输入的命名管道时挂起 为什么?

class comm(threading.Thread):

def __init__(self):
    self.srvoutf = './tmp/serverout'
    self.srvinf = './tmp/serverin'
    if os.path.exists(self.srvoutf):
        self.pipein = open(self.srvoutf, 'r') 
        #-----------------------------------------------------Hangs here
    else:
        os.mkfifo(self.srvoutf)
        self.pipein = open(self.srvoutf, 'r')
        #-----------------------------------------------------or here
    if os.path.exists(self.srvinf):
        self.pipeout = os.open(self.srvinf, os.O_WRONLY)
    else:
        os.mkfifo(self.srvinf)
        self.pipeout = os.open(self.srvinf, os.O_WRONLY)
        
    threading.Thread.__init__ ( self )

最佳答案

来自specification for open() :

When opening a FIFO with O_RDONLY or O_WRONLY set:

If O_NONBLOCK is set, an open() for reading-only shall return without delay. An open() for writing-only shall return an error if no process currently has the file open for reading.

If O_NONBLOCK is clear, an open() for reading-only shall block the calling thread until a thread opens the file for writing. An open() for writing-only shall block the calling thread until a thread opens the file for reading.

换句话说,当您打开命名管道进行读取时,默认情况下打开将阻塞,直到管道的另一端打开进行写入。要解决此问题,请使用 os.open() 并在命名管道的读取端传递 os.O_NONBLOCK

关于尝试打开命名管道进行读取时 Python 代码挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6241260/

相关文章:

python - 用dask对非常大的数据进行排序?

python - 当任何类型可以有零个元素时,元素类型组合的解决方案

python - 基于相关模型计数的Django过滤

复制文件并附加到另一个文件

linux - 如何在读取时为 Linux 中的命名管道运行命令?

linux - 是否可以在 Linux 上更改命名管道的大小?

python - 如何更新tensorflow中的 'eagertensor"对象

java - java中实用的参数文件读取

string - 如何使用批处理或 PowerShell 从文本文件中删除换行符

php include 来自 fifo(命名管道)文件的指令