Function Name:
select
Function signature:
select.select(readList, writeList, exceptionList[, timeOut])
Overview:
- The select.select() method provides the I/O multiplexing as provided by the Unix function call select().
- The select() function call in Unix, allows blocking on the readiness of multiple descriptors.
- select() is a system call. It tells the kernel to notify when any of the descriptors in the sets are ready for read/write/exception conditions.
- select() accepts three classes of descriptors as parameters on which it can block - the read set, the write set and the exception set.
- The descriptor could be any descriptor including File Descriptors and Sockets.
- select() unblocks when one of the following happens:
- When one of the descriptors from the read/write/exception sets are ready for a read, write operation or an exception has happened on the descriptor like a socket receiving out of band data on a TCP connection.
- When the specified time out occurs.
- If time specified is zero seconds then select() returns immediately returning the set of descriptors which are ready for read/write/exception condition. This enables implementing polling on the descriptors using select().
- When I/O needs to be performed on numerous descriptors it is inefficient to poll them using separate threads where each thread corresponds to processing a descriptor. Hence the routine select() is provided for I/O multiplexing.
Parameters:
readList: List of descriptors waiting for a condition when data is ready for read
writeList: List of descriptors waiting for a condition when data is ready for write
exceptionList: List of descriptors waiting for an exception condition
timeOut: Number of seconds to wait before coming out of blocking
Example:
import select import socket
# Class representing a log file class LogFile:
def __init__(self, logFileName, logFile, descriptor): self.myLogFileName = logFileName self.myLogFile = logFile self.myDescriptor = descriptor
# List of log files logFiles = []
file = open("LogFile1.txt", "w") logFile1 = LogFile("LogFile1.txt", file, file.fileno()) logFiles.append(logFile1)
file = open("LogFile2.txt", "w") logFile2 = LogFile("LogFile2.txt", file, file.fileno()) logFiles.append(logFile2)
file = open("LogFile3.txt", "w") logFile3 = LogFile("LogFile3.txt", file, file.fileno()) logFiles.append(logFile3)
# List of descriptors for read, write and exception conditions rdescriptors = [] wdescriptors = [] xdescriptors = []
# Add the write descriptors to the write descriptor list for log in logFiles: wdescriptors.append(log.myDescriptor)
# Wait for write condition rlist, wlist, xlist = select.select(rdescriptors, wdescriptors, xdescriptors)
print("Number of descriptors ready for write %d"%(len(wlist)))
# Write to all the logs that are ready for writeDescriptor in wlist: for log in logFiles: if log.myDescriptor is writeDescriptor: log.myLogFile.write("Starting to log events") |