Definition
select and poll are operating-system calls with which a program waits on several file descriptors §15.21 at once and wakes when at least one of them is ready or a time limit expires. A file descriptor is a small number that names an open file, pipe, network connection or device in a process. Ready for reading means that a read would not wait: it would return data, report end of file, or report an error. Python’s §12.23 select module provides them. Polling in general means checking repeatedly instead of sleeping until notified.
The idea
A program talks to a serial port, a network connection and the output pipe of a child process. If it calls read on the serial port, the call waits until the serial port has data, while bytes from the network pile up unanswered. One thread per descriptor works, but it multiplies threads and the locks between them. Checking each descriptor in turn without waiting, called busy polling, keeps the processor at full load even when nothing happens.
select and poll turn the question around: the program hands the kernel the whole list and sleeps until the kernel reports which descriptors can make progress. A restaurant pager is a fair picture. It buzzes when a table is ready, but the buzz does not promise that the whole party fits, and another guest may have taken the table by the time you arrive. Readiness is a statement about the next system call, not about the application’s messages. The picture stops at one point: a descriptor also counts as readable when the other side has closed it, because a read then returns at once with end of file.
How it works
An event loop §14.23 built on these calls repeats four steps.
Register interest. For each descriptor, state whether to watch it for reading, for writing, or for exceptional conditions.
Sleep.
select.select(rlist, wlist, xlist, timeout)takes three lists of descriptors and a timeout §9.34 in seconds (Nonewaits without limit,0checks without waiting) and returns three lists: the members of each that are ready.select.poll()returns an object instead. Its methodregister(fd, mask)records interest as bits such asPOLLIN(readable) andPOLLOUT(writable), and its methodpoll(ms)waits up to a number of milliseconds and returns pairs of a descriptor and its event bits. The bits can also includePOLLHUP(the other side hung up),POLLERR(an error) andPOLLNVAL(not an open descriptor), which are reported even when not requested. An empty result means that the timeout expired.Read. Perform one read on each ready descriptor, inspect what it returned, and append any bytes to that descriptor’s receive buffer.
Parse. Remove every complete record from the buffer, keep the rest, and go back to step 2.
What ready means. POSIX (Portable Operating System Interface) defines a descriptor as ready for reading when a read on it would not wait, whether or not the read would transfer data. One read on a ready descriptor can therefore produce:
between 1 byte and the number requested, being whatever the kernel holds at that moment: part of a record, one record, or several records and part of the next;
0 bytes, which means end of file (EOF): every writer has closed the pipe, or the peer of a stream connection has stopped sending;
an error, such as a connection reset by the peer;
for a listening network socket, a waiting connection that
acceptwill return.
Ready for writing means that a write would transfer at least some bytes without waiting; a large write can still be partial.
Variations. select and poll are level-triggered: they report a descriptor again on every call for as long as the condition holds. Regular disk files are always reported ready, because reading them never waits in this sense, so select cannot announce that a log file has grown. select accepts only descriptor numbers below a fixed limit, usually 1024, and its cost grows with the number of descriptors watched; poll has no such number limit. Linux’s epoll keeps the interest list inside the kernel and returns only the ready descriptors. In its edge-triggered mode it reports a descriptor only when new data arrives, so the program must read until a read reports that it would wait. On Windows, Python’s select.select accepts network sockets only. The selectors module picks the best call the system offers, and on Linux Python’s asyncio event loop is built on it.
Worked example
A protocol sends each record as a 2-byte big-endian §4.21 length, the most significant byte first, followed by that many payload bytes. The record 00 06 41 42 43 44 45 46 (hexadecimal) states the length and carries the 6 payload bytes ABCDEF, bytes in all. A receiver calls os.read(fd, 4096) on a pipe each time select reports the pipe readable.
The read returns 3 bytes,
00 06 41. The header says that the record needs 8 bytes, so are missing. No record yet.The read returns 10 bytes,
42 43 44 45 46 00 02 4F 4B 00. The buffer holds bytes. The first 8 form record 1,ABCDEF, leaving bytes,00 02 4F 4B 00. Their header states 2 payload bytes, so record 2 needs bytes and is complete:OK. byte,00, remains, the first half of a third header.The read returns 0 bytes: the writer has closed the pipe. One byte is still buffered, so the stream ended inside a record, and the receiver reports a truncated record instead of waiting for bytes that will never come. With an empty buffer, the same end of file would be a clean end.
Readiness was reported three times, the reads returned 3, 10 and 0 bytes, two records were delivered, and no readiness report fell on a record boundary.
On Linux, poll on that pipe, after the writer has closed it and the reader has emptied it, reports POLLHUP without POLLIN, while select lists the pipe as readable. A loop that reads only when it sees POLLIN never reads the end of file. Because POLLHUP makes every later poll return at once, such a loop spins at full processor load.
A serial port read through pyserial §12.36 with a timeout gives a contrast. There an empty result means that the timeout expired with no data, not that the stream ended. The meaning of an empty read depends on the kind of descriptor and its settings.
Stated precisely
Readiness for reading guarantees one thing: at the moment the kernel observed it, the next read on that descriptor would not wait. That read returns bytes with , where is the number requested; or , end of file; or an error. Let be the length of a record header, the payload length that the header states, and the number of bytes buffered for the descriptor. A record is complete exactly when , and readiness says nothing about .
The guarantee can lapse before the read. Another thread or process can read the same descriptor first, and the Linux manual page for select warns that a socket can be reported readable while a later read still waits, for example when arriving data is discarded because its checksum §4.32 is wrong. Descriptors used with select or poll should therefore be nonblocking (os.set_blocking(fd, False)), and a read that raises BlockingIOError then means only “not ready after all; wait again”.
Three facts are separate and need separate checks: the operating system’s readiness, the completeness of a record in the buffer, and the validity of the record. A complete record can still be malformed or come from a sender that may not send it.
Limits and common mistakes
Busy polling, such as calling select with timeout 0 in a loop, wastes processor time and battery energy. Give the call a real timeout, or none.
Remove a descriptor from the interest list before closing it. The number can be given to the next file the process opens, and the loop would then watch the wrong object. A closed descriptor left in the list makes select fail and poll report POLLNVAL.
select cannot watch descriptor numbers at or above its limit, usually 1024; Python raises ValueError for them. A process with many open files needs poll, epoll or the selectors module.
Readiness is not a receipt. That a peer’s data was readable, or that a write was accepted, shows nothing about whether the peer, or the application behind it, has processed anything.
Since Python 3.5, a call to select or poll that a signal cuts short is retried automatically with the remaining timeout, unless the signal handler raises an exception.
Questions answered
Does readability mean a full record is available, or possibly end of file?
Readability never means that a full record is available, and it can mean end of file. A descriptor is readable when a read call on it would not wait. That read may return a single byte, part of a record, several records, 0 bytes (end of file: every writer has closed the pipe, or the peer of a stream connection has stopped sending), or an error; when another reader gets there first, or in rare cases that the Linux select manual describes, it may even find nothing and wait. A receiver should therefore read in nonblocking mode, append the bytes to a buffer kept per descriptor, take out records only when the buffer holds a whole one according to the framing rule, treat 0 bytes as end of file (and report a truncated record if the buffer is not empty), and validate each record separately. One exception to the end-of-file reading: a terminal device in noncanonical mode, or a serial library such as pyserial with a timeout, returns 0 bytes when nothing arrived in time, which is not end of file.
Related entries: pyserial (§12.36), termios and tty (§12.42), Event loop (§14.23), Length-prefix framing (§4.30), Deadline versus timeout (§9.34). Further reading: [38].