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

12 投票
1 回答
9501 浏览
提问于 2025-04-16 18:58

我正在尝试通过命名管道建立一个守护进程和客户端之间的双向通信。但是在尝试打开用于输入的命名管道时,代码卡住了,为什么会这样呢?

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 )

1 个回答

14

根据open()的规范

当你用O_RDONLY(只读)或O_WRONLY(只写)打开一个FIFO(命名管道)时:

如果设置了O_NONBLOCK(非阻塞),那么只读的open()会立即返回,不会等待。如果是只写的open(),如果没有其他进程在读取这个文件,就会返回一个错误。

如果没有设置O_NONBLOCK,那么只读的open()会一直等待,直到有其他线程打开这个文件进行写入。而只写的open()也会一直等待,直到有其他线程打开这个文件进行读取。

换句话说,当你打开一个命名管道进行读取时,默认情况下,这个操作会一直等待,直到管道的另一端被打开进行写入。要解决这个问题,可以使用os.open()并在命名管道的读取端传入os.O_NONBLOCK

撰写回答