开发者

Python code hangs while trying to open a named pipe for reading [duplicate]

This question already has an answer here: Why does a read-only open of a named pipe block? (1 answer) Closed 2 years ago.

I am trying to setup two way communication between a daemon and a client using named pipes. The code hangs while trying to open the named pipe used for input Why?

class comm(threading.Thread):

def __init__(self):
    self.srvoutf = './tmp/开发者_如何学Goserverout'
    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 )


From the 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.

In other words, when you open a named pipe for reading, by default the open will block until the other side of the pipe is opened for writing. To fix this, use os.open() and pass os.O_NONBLOCK on the read side of the named pipe.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜