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

2024-04-27 23:24:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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 )

Tags: pathselfif管道initosexistsopen
1条回答
网友
1楼 · 发布于 2024-04-27 23:24:35

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

相关问题 更多 >