In the process of programming, often encounter many blocking functions, as read and network programming use of the recv, recvfrom functions are blocking functions, when the function is not successful execution, the program will always block here, unable to execute the following code. This is the need to use non-blocking programming, using the SELCET function can be implemented non-blocking programming.
The Selcet function is a round robin function, that is, when a loop asks for a file node, you can set the timeout time, and the timeout time to skip the code and continue to execute.
Example:
Fd_set READFD;
struct Timeval timeout;
Fd_zero (&READFD); Initialization of READFD
fd_set (GPS_FD, &READFD); Add GPS_FD to READFD
timeout.tv_sec = 3; Set 3 seconds timeout
timeout.tv_usec = 0;
j = Select (Gps_fd+1, &READFD, NULL, NULL, &timeout); Use Select to Gps_fd if
(j>0) {if (
fd_isset (GPS_FD, &READFD)) { //if gps_fd readable
i = Read (GPS _FD, buf, SIZE);
Buf[i] = ' = ';
}
}
The Select function has 5 parameters
The first is the maximum of all file nodes plus 1, if I have three file nodes 1, 4, 6, the first argument is 7 (6+1)
The second is a set of readable file nodes, with a type of fd_set. by Fd_zero (&READFD), initializing the node set, and then passing Fd_set (FD, &READFD), joining the node set to listen for the readable nodes
The third is a writable file node set, with a type of fd_set. The action method is the same as the second argument.
The fourth parameter is to check the node error set.
The fifth parameter is the timeout parameter, the type is struct timeval, and then the timeout can be set to set the seconds timeout.tv_sec and microseconds timeout.tv_usec respectively.
The Select function is then invoked and the Fd_isset () function is used to determine whether the node is readable or writable. A return value of not 0 indicates a read-write and a 0 is not writable. The return value of the Select function is an integer indicating that several nodes are readable and writable.