[Twisted-Python] How does the pollreactor work?

glyph at divmod.com glyph at divmod.com
Fri Aug 29 17:20:34 EDT 2008


On 03:35 pm, rlott at evertz.com wrote:
>I have been trying to figure out how to use the 
>twisted.internet.pollreactor so that I can use it to monitor a Linux 
>named PIPE (i.e. a FIFO created using mkfifo()).  I tried without 
>success to Google some examples but I couldn't find anything.

This doesn't really have anything to do with pollreactor.  Any reactor 
that implements IReactorFDSet can monitor a pipe.

It was easier for me to implement this than to explain what to do, so 
here's the code for monitoring a named pipe for read, given its name. 
I'm pretty sure it's not 100% correct, but if you want to read about 
handling I/O events from fifos on your platform, you are welcome to do 
so.

    import os
    from twisted.internet.abstract import FileDescriptor
    from twisted.internet.main import CONNECTION_DONE

    class FIFODescriptor(FileDescriptor):
        def __init__(self, reactor, fifoname, protocol):
            FileDescriptor.__init__(self, reactor)
            self.fifo = os.open(fifoname, os.O_NONBLOCK | os.O_RDONLY)
            self.protocol = protocol
            self.protocol.makeConnection(self)

        def connectionLost(self, reason):
            self.protocol.connectionLost(reason)

        def doRead(self):
            data = os.read(self.fifo, 1024)
            if data:
                self.protocol.dataReceived(data)
            else:
                self.stopReading()
                self.connectionLost(CONNECTION_DONE)

        def fileno(self):
            return self.fifo


And here's a brief program that uses it:

    import sys
    from twisted.internet import reactor
    from twisted.internet.protocol import Protocol
    class PrintingProtocol(Protocol):
        def dataReceived(self, data):
            print 'data', repr(data)
        def connectionMade(self):
            print 'hi'
        def connectionLost(self, reason):
            print 'bye', reason
    fifd = FIFODescriptor(reactor, sys.argv[1], PrintingProtocol())
    fifd.startReading()
    reactor.run()

I tested this by doing 'mkfifo x; python fifo.py x', and in another 
terminal, 'cat > x'.  It should be pretty self-explanitory.




More information about the Twisted-Python mailing list