Polling, Fifos, and Linux

Remi Villatel maxilys at SPAMCOP_tele2.fr
Sat Jul 9 02:38:42 CEST 2005


Jeremy Moles wrote:

> This is my first time working with some of the more lower-level python
> "stuff." I was wondering if someone could tell me what I'm doing wrong
> with my simple test here?
> 
> Basically, what I need is an easy way for application in userspace to
> simply echo values "down" to this fifo similar to the way proc files are
> used. Is my understanding of fifo's and their capabilities just totally
> off base?

Funny coincidence... I was also trying some FIFO stuff today. I came to a 
very simple solution for just one writer and one listener. I make this stuff 
send text (strings) from one Konsole to another Konsole.

The FIFO was created from Bash with:

$ mkfifo -m 666 fifo

listener.py
------------------
#! /usr/bin/env python

fifo = open("fifo","r")

while True:
	print fifo.readline()[:-1]
	# [:-1] because of the newline added by print.
#
------------------

writer.py
------------------
#! /usr/bin/env python

fifo = open("fifo", "a")	# Mode "a" or "w"

try:
	fifo.write("This string goes down the pipe.\n")
	# Newline is important because the listener uses readline().
	fifo.flush()
	# Output is buffered.
except IOError:
	pass
#
------------------

If you kill the writer, the listener remains quiet until somebody writes 
into the pipe. The same happens if there is no writer.

If you kill the listener, the writer reports a broken pipe when it tries to 
flush().

The writer can close and open the pipe to its liking, the listener doesn't care.

The only problem is that the writer freezes when it opens the pipe until 
there is a listener at the other end.

Any way, it's very simple and it uses 0% of the CPU.

Just my 2 Euro cents,

-- 
==================
Remi Villatel
maxilys_ at _tele2.fr
==================



More information about the Python-list mailing list