Detailed use of the Select function (C language)

Source: Internet
Author: User

Select in the socket programming is still more important, but for beginners socket people are not too fond of using select Write program, they just used to write such as Connect, accept, Blocking programs such as recv or recvfrom (the so-called block mode block, as the name implies, is that a process or thread must wait for an event to occur when it executes to these functions, and if the event does not occur, the process or thread is blocked and the function cannot be returned immediately). However, a non-blocking (so-called nonblocking mode non-block is done using SELECT, that is, the process or thread does not have to wait for the event to occur, and once the execution is returned, the return value is different to reflect the execution of the function, if the event occurs in the same way as the block. If the event does not occur, return a code to tell the event not to occur, and the process or thread continues to execute, so it is more efficient to work on the program, which can monitor the change of the file descriptor we need to monitor-read-write or exception.

function format for select:

int select (int maxfdp,fd_set *readfds,fd_set *writefds,fd_set *errorfds,struct timeval*timeout);
First, the two structures:
Firstly, struct fd_set can be understood as a collection, which holds the file descriptor (FileDescriptor), that is, the file handle, which can be what we call the ordinary meaning of the file, Of course, UNIX under any Device, pipeline, FIFO, etc. are file forms, all included, so there is no doubt that a socket is a file, the socket handle is a file descriptor. The Fd_set collection can be manipulated by some macros, such as emptying the set Fd_zero (Fd_set *), adding a given file descriptor to the collection fd_set (int, fd_set*), removing a given file descriptor from the collection fd_clr (int, fd_set*), checks whether the specified file descriptor in the collection can read and write Fd_isset (int, fd_set*).

second, struct timevalis a commonly used structure that represents a time value, has two members, one is the number of seconds, and the other is the number of milliseconds.
Explain the parameters of select in detail:int MAXFDP is an integer value that refers to the range of all file descriptors in the collection, that is, the maximum value of all file descriptors plus 1, not wrong! The value of this parameter in Windows does not matter and can be set incorrectly.
Fd_set * Readfds is a pointer to the FD_SET structure, which should include the file descriptor, we want to monitor the read changes of these file descriptors, that is, we care whether the data can be read from these files, if there is a file in this collection is readable, Select returns a value greater than 0, indicating that the file is readable, and if there is no readable file, the timeout parameter is used to determine whether to time out, and if timeout is exceeded, select returns 0 if an error returns a negative value. You can pass in a null value to indicate that you do not care about any file read changes.
Fd_set * Writefds is a pointer to the FD_SET structure, which should include the file descriptor, we want to monitor the write changes of these file descriptors, that is, we care about whether the data can be written to these files, if there is a file in this collection can be written, Select returns a value greater than 0, indicating that a file is writable, and if there is no writable file, the timeout parameter is used to determine whether to time out, and if timeout is exceeded, select returns 0 if an error returns a negative value. You can pass in a null value to indicate that you do not care about any file write changes.
Fd_set * Errorfds with the above two parameter intent, to monitor file error exceptions.
struct Timeval * Timeout is the time-out for Select, which is critical, which allows the select to be in three states, first, if NULL is passed as a parameter, that is, the time structure is not passed in, the select is put in a blocking state, Be sure to wait until one of the file descriptors in the monitor file descriptor collection changes; second, if the time value is set to 0 seconds 0 milliseconds, it becomes a purely non-blocking function, regardless of whether the file descriptor is changed, immediately return to continue execution, the file has no change return 0, there is a change to return a positive value; Timeout value is greater than 0, this is the waiting time-out period, that is, select in timeout time block, the timeout period has the arrival of the event to return, otherwise after the timeout, anyway must return, the return value with the above.

struct Timeval{long tv_sec;//Secondslong tv_usec;//microseconds}

return Value: Returns the total number of descriptors for which the status has changed. Negative Value: Select Error

Positive values: Some files are read-write or error-prone

0: Wait timeout, no writable or incorrect files

Parameter interpretation

Readset Writeset Exceptset Specifies the descriptor we want the kernel to test for read, write, and exception conditions. If you are not interested in a certain condition, you can set it to null. If all three pointers are null, we have a timer that is more precise than the sleep () function (sleep () is the smallest unit in milliseconds, in microseconds. Select uses a descriptor set, typically an array of integers, where each bit in each integer corresponds to a descriptive word. Assuming that a 32-bit integer is used, the first element of the array corresponds to the descriptor 0~31, the second element corresponds to the description word 32~63, and so on. All implementation details are application-agnostic, and they are hidden in the data type named Fd_set and the following four macros: void Fd_zero (Fd_set *fdset); Clear all bits in fdsetvoid fd_set (int fd,fd_set *fdset); Turn on the bit for FD in fdsetvoid fd_clr (int fd,fd_set *fdset); Turn off the bit for FD in fdsetintfd_isset (int fd,fd_set *fdset); is the bit for FD on in FdsetDetailed IntroductionThe function format of select (I'm talking about the Berkeley socket programming under UNIX systems, and the difference under Windows, explained later): int maxfdp,fd_set *readfds,fd_set *writefds, Fd_set *errorfds,struct timeval *timeout); First, the struct fd_set can be understood as a collection, which holds the file descriptor (filedescriptor), the file handle, This can be what we call the ordinary meaning of the file, of course, UNIX under any Device, pipeline, FIFO, etc. are file forms, all included, so there is no doubt a socket is a file, the socket handle is a file descriptor. The Fd_set collection can be manipulated by some macros, such as emptying the set Fd_zero (Fd_set *), adding a given file descriptor to the collection fd_set (int,fd_set*); Removing a given file descriptor from the collection fd_clr (int, fd_set*) checks whether the specified file descriptor in the collection can read and write Fd_isset (int,fd_set*). A moment to illustrate. Second, struct timeval is a common structure that is used to represent time values, have two members, one is seconds, and the other is a subtle number. Specify the parameters of select: Int MAXFDP is an integer value that refers to the range of all file descriptors in the collection, that is, the maximum value of all file descriptors plus 1, cannot be wrong! The value of this parameter in Windows does not matter and can be set incorrectly. Fd_set*readfds is a pointer to the FD_SET structure, which should include the file descriptor, we want to monitor the read changes of these file descriptors, that is, we care whether the data can be read from these files, if there is a file in this collection is readable, Select returns a value greater than 0, indicating that the file is readable, and if there is no readable file, the timeout parameter is used to determine whether to time out, and if timeout is exceeded, select returns 0 if an error returns a negative value. You can pass in a null value to indicate that you do not care about any file read changes. Fd_set*writefds is a pointer to the FD_SET structure, which should include the file descriptor, we want to monitor the write changes of these file descriptors, that is, we care whether the data can be written to these files, if there is a file in this collection can be written, Select returns a value greater than 0, indicating that a file is writable, and if there is no writable file, then it is judged by the timeout parameterNo timeout, if timeout time is exceeded, select returns 0 if an error returns a negative value. You can pass in a null value to indicate that you do not care about any file write changes. Fd_set *errorfds with the above two parameters to monitor file error exceptions. The struct Timeval *timeout is the time-out for Select, which is critical, which allows the select to be in three states, first, if NULL is passed in as a parameter, that is, the time structure is not passed in, the select is put in a blocking state, Be sure to wait until one of the file descriptors in the monitor file descriptor collection changes; second, if the time value is set to 0 seconds 0 milliseconds, it becomes a purely non-blocking function, regardless of whether the file descriptor is changed, immediately return to continue execution, the file has no change return 0, there is a change to return a positive value; Timeout value is greater than 0, this is the waiting time-out period, that is, select in timeout time block, the timeout period has the arrival of the event to return, otherwise after the timeout, anyway must return, the return value with the above. Return values: Negative value: Select Error positive values: Some files can be read or write or error 0: Wait timeout, no read or write or error files after having a select can write a decent network program! As a simple example, the acceptance of data from the network is written to a file. Example:
Main () {int sock;IntFd;fd_set FDS;struct Timeval timeout={0,3};//Select Waits 3 microseconds, 3 microseconds for polling, 0 for non-blockingChar buffer[256]={0};//256-byte Receive buffer/*Assuming that the UDP connection has been established, the specific process is not written, simple, of course, TCP is also the same, the host IP and port are given, the file to be written has been opened Sock=socket (...); Bind (...); Fd=open (...);*/While⑴{fd_zero (&fds);//The collection must be emptied for Each loop, otherwise the descriptor change Fd_set (SOCK,&FDS) cannot be detected;//Add descriptor Fd_set (FD,&FDS);//Ditto timeout.tv_sec=3; timeout.tv_usec=0;//The SELECT function constantly modifies the value of timeout so that each loop should be re-assigned [Windows is unaffected by this]maxfdp=sock>fd?sock+1:fd+1;//Descriptor Maximum Value plus 1SwitchSelect (Maxfdp,&fds,&fds,null,&timeout))//Select Uses{Case-1:exit (-1);Break//Select error, exiting the programCase0:Break//Poll againDefault:if (Fd_isset (Sock,&fds)) // {recvfrom (Sock,buffer,256,.....); // Accept network data if (FD, &fds)) // test file writable write (Fd,buffer ...); // write file buffer empty;}// End If break;} // end Switch}//end while}//end main   
The relationship between the Select () function and the Linux driver when the user invokes the select system call, the select system call calls Poll_initwait (&table) and then calls the driver in the struct FILE_ The Fop->poll function under operations should call Poll_wait () in this function, add current to a waiting queue (call poll_wait () here), and check if it is valid and call Schedule_ if it is not valid. Timeout (); Go to sleep. After the event occurs, Schedule_timeout () comes back, calls Fop->poll (), checks to be able to run, invokes Poll_freewait (&table), and completes the select system call. It is important to check if the Fop->poll () is ready, and if so, to return the corresponding flag.

Category: Network programming

Detailed use of the Select function (C language)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.