The select system call

The select system call is used in multiplexed I/O. The select system call blocks on a set of File descriptors (FD) until one of the FDs is ready for read/write.

The select system call is provided below

FIG Courtesy : The Linux Programming Interface – Michael Kerrisk

The parameters of the API are explained below. The readfs, writefds and exceptfds are a list of File descriptors and are termed fdsets.  fdsets are bitmasks. The FD_SETSIZE parameter determines how many bits are present in the bitmask. the typical value of FS_SETSIZE is 1024.

  • nfds – highest file descriptor number registered to select call + 1
  • readfds – set of file descriptors to be tested if input to application is possible
  • writefds – set of file descriptors to be tested if output from application is possible
  • exceptfds – fd to monitor state change in pseudoterminal or out of band data received on a stream socket
  • timeout – maximum value till which time select call will block 

To set the various parameters of the select API call, four macros are defined. They are:

  • FD_ZERO – initialize the set pointed by the relevant fdset
  • FD_SET – adds the file descriptor fd in the bitmask  pointed to by fdset
  • FD_CLR –  clears the file descriptor fd in the bitmask pointed by fdset.
  • FD_ISSET – checks if a particular fd is set in the bitmask pointed by fdset 

Before the call to select the “fdsets of interest” need to be initialized with FD_ZERO and FD_SET needs to be invoked on the fdsets to register the File descriptors that the application has an interest in monitoring. if a particular fdset is not needed to be monitored, that particular fdset parameter is set to NULL in the call to select API.  

The timeout parameter can be set to a value (time till which select will block) or set to NULL (select blocks indefinitely). If timeout is not NULL but set to 0 seconds and microseconds, the select call will not block but just poll the file descriptors to check which file descriptors are ready and returns immediately. The timeout structure is shown below

FIG Courtesy: The Linux Programming Interface – Michael Kerrisk

The following article provides an example usage of the select system call.

Select System Call API Code Example

References: The Linux Programming Interface – Michael Kerrisk

Comments

  1. Pingback: Select and Poll API | Hitch Hiker's Guide to Learning

  2. Pingback: Select System Call API Code Example | Hitch Hiker's Guide to Learning

  3. Pingback: The Poll System call | Hitch Hiker's Guide to Learning

Leave a Reply

Your email address will not be published. Required fields are marked *