Copyright © tutorialspoint.com
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *utimeout);
int pselect(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, const struct timespec *ntimeout, sigset_t *sigmask);
FD_CLR(int fd, fd_set *set);
FD_ISSET(int fd, fd_set *set);
FD_SET(int fd, fd_set *set);
select() (or pselect()) is the pivot function of most C programs that handle more than one simultaneous file descriptor (or socket handle) in an efficient manner. Its principal arguments are three arrays of file descriptors: readfds, writefds, and exceptfds. The way that select() is usually used is to block while waiting for a "change of status" on one or more of the file descriptors. A "change of status" is when more characters become available from the file descriptor, or when space becomes available within the kernels internal buffers for more to be written to the file descriptor, or when a file descriptor goes into error (in the case of a socket or pipe this is when the other end of the connection is closed).
In summary, select() just watches multiple file descriptors, and is the standard Unix call to do so.
The arrays of file descriptors are called file descriptor sets. Each set is declared as type fd_set, and its contents can be altered with the macros FD_CLR(), FD_ISSET(), FD_SET(), and FD_ZERO(). FD_ZERO() is usually the first function to be used on a newly declared set. Thereafter, the individual file descriptors that you are interested in can be added one by one with FD_SET(). select() modifies the contents of the sets according to the rules described below; after calling select() you can test if your file descriptor is still present in the set with the FD_ISSET() macro. FD_ISSET() returns non-zero if the descriptor is present and zero if it is not. FD_CLR() removes a file descriptor from the set.
|This set is watched to see if data is available for reading from any of its file descriptors. After select() has returned, readfds will be cleared of all file descriptors except for those file descriptors that are immediately available for reading with a recv() (for sockets) or read() (for pipes, files, and sockets) call.|
|This set is watched to see if there is space to write data to any of its file descriptors. After select() has returned, writefds will be cleared of all file descriptors except for those file descriptors that are immediately available for writing with a send() (for sockets) or write() (for pipes, files, and sockets) call.|
|This set is watched for exceptions or errors on any of the file descriptors. However, that is actually just a rumor. How you use exceptfds is to watch for out-of-band (OOB) data. OOB data is data sent on a socket using the MSG_OOB flag, and hence exceptfds only really applies to sockets. See recv(2) and send(2) about this. After select() has returned, exceptfds will be cleared of all file descriptors except for those descriptors that are available for reading OOB data. You can only ever read one byte of OOB data though (which is done with recv()), and writing OOB data (done with send()) can be done at any time and will not block. Hence there is no need for a fourth set to check if a socket is available for writing OOB data.|
|nfds||This is an integer one more than the maximum of any file descriptor in any of the sets. In other words, while you are busy adding file descriptors to your sets, you must calculate the maximum integer value of all of them, then increment this value by one, and then pass this as nfds to select().|
This is the longest time select() must wait before returning, even
if nothing interesting happened. If this value is passed as NULL,
then select() blocks indefinitely waiting for an event.
utimeout can be set to zero seconds, which causes select() to
return immediately. The structure struct timeval is defined as,
This argument has the same meaning as utimeout but struct timespec
has nanosecond precision as follows,
|This argument holds a set of signals to allow while performing a pselect() call (see sigaddset(3) and sigprocmask(2)). It can be passed as NULL, in which case it does not modify the set of allowed signals on entry and exit to the function. It will then behave just like select().|
int child_events = 0;
A simple example of the use of select() can be found in the select(2) manual page.
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/time.h> #include <sys/types.h> #include <string.h> #include <signal.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h>
The above program properly forwards most kinds of TCP connections including OOB signal data transmitted by telnet servers. It handles the tricky problem of having data flow in both directions simultaneously. You might think it more efficient to use a fork() call and devote a thread to each stream. This becomes more tricky than you might suspect. Another idea is to set non-blocking I/O using an ioctl() call. This also has its problems because you end up having to have inefficient timeouts.
The program does not handle more than one simultaneous connection at a time, although it could easily be extended to do this with a linked list of buffers one for each connection. At the moment, new connections cause the current connection to be dropped.
|1.||You should always try to use select() without a timeout. Your program should have nothing to do if there is no data available. Code that depends on timeouts is not usually portable and is difficult to debug.|
|2.||The value nfds must be properly calculated for efficiency as explained above.|
|3.||No file descriptor must be added to any set if you do not intend to check its result after the select() call, and respond appropriately. See next rule.|
|4.||After select() returns, all file descriptors in all sets should be checked to see if they are ready.|
|5.||The functions read(), recv(), write(), and send() do not necessarily read/write the full amount of data that you have requested. If they do read/write the full amount, its because you have a low traffic load and a fast stream. This is not always going to be the case. You should cope with the case of your functions only managing to send or receive a single byte.|
|6.||Never read/write only in single bytes at a time unless your are really sure that you have a small amount of data to process. It is extremely inefficient not to read/write as much data as you can buffer each time. The buffers in the example above are 1024 bytes although they could easily be made larger.|
|7.||The functions read(), recv(), write(), and send() as well as the select() call can return -1 with errno set to EINTR, or with errno set to EAGAIN (EWOULDBLOCK). These results must be properly managed (not done properly above). If your program is not going to receive any signals then it is unlikely you will get EINTR. If your program does not set non-blocking I/O, you will not get EAGAIN. Nonetheless you should still cope with these errors for completeness.|
|8.||Never call read(), recv(), write(), or send() with a buffer length of zero.|
|9.||If the functions read(), recv(), write(), and send() fail with errors other than those listed in 7., or one of the input functions returns 0, indicating end of file, then you should not pass that descriptor to select() again. In the above example, I close the descriptor immediately, and then set it to -1 to prevent it being included in a set.|
|10.||The timeout value must be initialized with each new call to select(), since some operating systems modify the structure. pselect() however does not modify its timeout structure.|
|11.||I have heard that the Windows socket layer does not cope with OOB data properly. It also does not cope with select() calls when no file descriptors are set at all. Having no file descriptors set is a useful way to sleep the process with sub-second precision by using the timeout. (See further on.)|
struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 200000; /* 0.2 seconds */ select (0, NULL, NULL, NULL, &tv);
This is only guaranteed to work on Unix systems, however.
If select() timed out, then the return value will be zero. The file descriptors set should be all empty (but may not be on some systems).
A return value of -1 indicates an error, with errno being set appropriately. In the case of an error, the returned sets and the timeout struct contents are undefined and should not be used. pselect() however never modifies ntimeout.
The poll(2) system call has the same functionality as select(), and is somewhat more efficient when monitoring sparse file descriptor sets. It is nowadays widely available, but historically was less portable than select().
The Linux-specific epoll(7) API provides an interface that that is more efficient than select(2) and poll(2) when monitoring large numbers of file descriptors.
Copyright © tutorialspoint.com