Does a python fifo have to be read with os.open?

1.5k views Asked by At

I am experimenting with using fifos for IPC routines in Python, and have the following code to create the fifo, then start two threads to write to it at varying times and read continually from it to print out whatever is put on the fifo.

It works when the fifo is read using os.open(); however, I'm reading through O'Reilly's "Programming Python 4th Edition" where they claim the fifo can be opened as a text file object by the "consumer" process.

In here, switching the "consumer" thread to target the "consumer2" function attempts to read the fifo as a text object, instead of using os.open. However, when read in this way, the program is blocked when the "readline" method is called.

Is there a way to read a fifo in as a text object, or does it always have to be read in using os.open?

import os, time, threading

fifofile = '/tmp/thefifo'
if not os.path.exists(fifofile):
    os.mkfifo(fifofile)

def producer():
    num = 0
    fifo_out = os.open(fifofile, os.O_WRONLY) #open the fifo for writing
    while True:
        time.sleep(num)
        os.write(fifo_out, "".join(["Message  ",str(num)]).encode())
        num = (num + 1) % 5

def consumer():
    fifo_in = os.open(fifofile, os.O_RDONLY)
    while True:
        line = os.read(fifo_in, 24)
        print("Read: %s" % line.decode())

def consumer2():
    fifo_in = open(fifofile, "r") #open for reading as text object...
    while True:
        line = fifo_in.readline()[:-1] #read an available line on the fifo...
        print("Line read: %s" % line)

#Thread the calls...
producerTH = threading.Thread(target=producer)
consumerTH = threading.Thread(target=consumer) #using consumer2 does not work
producerTH.start()
consumerTH.start()

For this, I am using Python 3.4.3 in OS X 10.10.3.

1

There are 1 answers

2
Kenji Noguchi On BEST ANSWER

You just need os.write(fifo_out, "\n".encode()) after writing the message because readline expects the "\n"