How does polling a file for changes work?

Problem

I expected the script below to print no more than one event and then stop (it is written only to illustrate the problem).

#!/usr/bin/env python from select import poll, POLLIN filename = "test.tmp" # make sure file exists open(filename, "a").close() file = open(filename, "r+") p = poll() p.register(file.fileno(), POLLIN) while True: events = p.poll(100) for e in events: print e # Read data, so that the event goes away? file.read() 

However, it prints about 70,000 events per second. Why?

Background

I wrote a class that uses the pyudev.Monitor class internally. Among other things, it will poll fileno, provided by the fileno () method for changes, using the polling object.

Now I am trying to write unit test for my class (I understand that I have to write unit test first, so I do not need to specify it), and therefore I need to write my own fileno () for my mock pyudev.Monitor object, and I need to manage it so that I can initiate a polling object to report the event. As the above code shows, I can't get it to stop reporting seemingly non-existent events!

I cannot find ident_event () or similar in the polling class to exclude an event (I suspect there is only one event that somehow got stuck), a google search and this site did not return anything. I am using python 2.6.6 on Ubuntu 10.10.

+6
python polling udev
source share
1 answer

You will be able to use pipes, not files. Try instead:

 #!/usr/bin/env python import os from select import poll, POLLIN r_fd, w_fd = os.pipe() p = poll() p.register(r_fd, POLLIN) os.write(w_fd, 'X') # Put something in the pipe so p.poll() will return while True: events = p.poll(100) for e in events: print e os.read(r_fd, 1) 

This will print out the only event you are looking for. To trigger a polling event, all you have to do is write a byte to the file descriptor.

+3
source share

All Articles