A detailed analysis of select function and Case study __ function

Source: Internet
Author: User
Tags assert readable

http://blog.csdn.net/leo115/article/details/8097143

The Select function is still more important in the socket programming, but for beginners of the socket are not too fond of using Select to write programs, they are only accustomed to writing such as Connect, accept, Blocking programs such as recv or recvfrom (the so-called blocking mode block, as the name suggests, is that processes or threads must wait for an event to occur when the function is executed, and if the event does not occur, the process or thread is blocked and the function cannot return immediately). But using a select allows you to do non-blocking (the so-called non-blocking Non-block, where a process or thread performs this function without having to wait for the event to occur, once the execution returns, to reflect the difference in the value of the function, and if the event occurs the same way as blocking, 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 the more efficient way to work the program, it can monitor the change of the file descriptor we need to monitor-read-write or abnormal. Here is a detailed description.

Two structures are described first:

1, the Select mechanism provides a data structure struct fd_set, can be understood as a collection, is actually a bitmap, each specific to flag the corresponding size file descriptor, this collection is a file descriptor (Files descriptor), that is, file handle ( That is, each bit of the bitmap can be contacted with an open file handle (file descriptor), this work is done by programmers, and this can be what we call the common sense 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, and the socket handle is a file descriptor. The Fd_set collection can be manipulated by some macros, and programmers perform the most fd_set actions by manipulating 4-class macros:

(1), Fd_zero (Fd_set *) empties a collection of file descriptors;

(2), fd_set (int, fd_set *) adds a file descriptor to a specified set of file descriptors;

(3), fd_clr (int, fd_set*) deletes a given file descriptor from the collection;

(4), fd_isset (int, fd_set*) checks whether the specified file descriptor in the collection can read or write.

The key point of understanding the Select model in depth is to understand fd_set, in order to illustrate the convenience, we take fd_set length of 1 bytes, fd_set each bit can correspond to a file descriptor FD. The maximum of 1-byte fd_set can correspond to 8 FD.

(1) Execute Fd_set set;fd_zero (&set); The set is represented by a bit as 0000,0000.

(2) If FD = 5, then after executing fd_set (fd,&set), the SET becomes 0001,0000 (the 5th position is 1)

(3) If the addition of fd=2, Fd=1, then set into 0001.0011

(4) Execute select (6,&set,0,0,0) blocking wait

(5) If a readable event occurs on the fd=1,fd=2, the select returns, and the set becomes 0000,0011. FD = 5 was emptied when no readable event occurred. 2, struct timeval, a commonly used structure, to represent the time value, there are two members, one is the number of seconds, the other is the number of milliseconds.

[CPP] view plain copy struct Timeval {long tv_sec;   Second long tv_usec;   Microsecond}; The precision of this structure can be as accurate as 1 seconds.

Next, we'll introduce the SELECT function, which has the function format:

[CPP] view plain copy int select (int maxfdp,fd_set *readfds,fd_set *writefds,fd_set *errorfds,struct timeval *ti Meout);

To explain the parameters of a select specifically:

(1) 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.

Note: The explanation of this principle can be seen in the detailed explanation of the above Fd_set, Fd_set is the form of bitmap to store these file descriptors. MAXFDP defines the number of bits in a bitmap that are valid.

(2) Fd_set *readfds is a pointer to the FD_SET structure, which should include a file descriptor that we want to monitor for read changes to these file descriptors, that is, we care about whether we can read the data from these files, if there is a file in the collection that is readable, The select returns a value greater than 0 to indicate that there is a file readable and, if there is no readable file, to determine whether the timeout is based on the timeout parameter, and if the 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 read changes to any file.

(3) Fd_set *writefds is a pointer to the FD_SET structure, which should include a file descriptor, and we want to monitor the write changes of these file descriptors, that is, we care about whether we can write data to these files, if there is a file in the collection that can be written, Select returns a value greater than 0, indicating that there is a file to write, if there is no writable file, then the timeout parameter to determine whether to timeout, if more than timeout time, select return 0, if an error returns a negative value. You can pass in a null value, indicating that you don't care about any file's write changes.

(4) The intent of the Fd_set *errorfds with the above two parameters to monitor file error exception files.

(5) struct timeval* timeout is the timeout for select, which is critical in that it enables the select to be in three states, first, if NULL is passed in as a formal parameter, without passing in the time structure, the select is placed in a blocking state, Be sure to wait until a file descriptor in the collection of the monitor file descriptor changes; second, if the time value is set to 0 seconds 0 milliseconds, it becomes a pure non-blocking function, regardless of whether the file descriptor changes, immediately return to continue execution, the file does not change the return of 0, there are changes to return a positive; third, The value of the timeout is greater than 0, which is the timeout for the wait, that is, the select is blocked in the timeout time and the event comes back within the timeout period, otherwise it will be returned after the timeout, and the return value is the same as above.

Description

function returns:

(1) The Kernel (I/O) modifies the file descriptor set according to state and returns a number greater than 0 when the corresponding file descriptor for monitoring satisfies the condition, such as when data arrives in the read file descriptor set.

(2) The Select function returns a value of 0 when no file descriptor satisfies the condition, and the set Timeval monitoring time times out.

(3) An error occurred when the select returned a negative value.

Some reference analysis of the Select function: http://www.groad.net/bbs/read.php?tid-1064.html

the difference between the Select function and the Pselect function reference: http://hi.baidu.com/_jiangming/item/56d5c43fe2cadb4981f1a789

the Pselect function is an enhanced select function that prevents signal interference.

Select () Function instance analysis:

(1) After having a select, you can write a decent network program. A simple example is to accept data from a network to write to a file.

[CPP] View plain Copy Int main ()    {       int sock;    & nbsp;  file *fp;       struct fd_set fds;       struct timeval timeout={3,0}; //select wait 3 seconds, 3 seconds polling, to be non-blocking 0       char buffer[256]={0}; //256 bytes Receive buffer        /*   Assume that the UDP connection has been established, the specific process does not write, simple, of course, TCP also the same, host IP and port have been given, to write the file has been opened       sock=socket (...);       bind (...);       fp=fopen (...);  */       while (1)        {            fd_zero (&fds)  //to empty the collection every time the loop is not detected, the descriptor changes             fd_set (Sock,&fds);  //Add descriptor             fd_set (Fp,&fds)  //ditto            MAXFDP=SOCK>FP?SOCK+1:FP +1; //descriptor Max plus 1           switch (select Maxfdp,&fds, &fds,null,&timeout)  //select use            {                case -1: exit (-1 ); Break; //select error, exit program                 case 0:break; //again polling                 default:               if (fd_ ISSET (SOCK,&FDS))  //Test Sock is readable, that is, whether there is data on the network                 {                  &nBsp; recvfrom (sock,buffer,256,.....); /Accept Network Data                         if (Fd_isset (FP,&FDS))  //test file is writable                     fwrite (Fp,buffer ...); /write Files                     //buffer Clear;               }//  end if break;           }// end switch        }//end while  }//end main  


(2) Linux monitor the keyboard on whether there is data arrival.

[CPP] View plain copy #include  <sys/time.h>   #include  <stdio.h>   #include  <sys/types.h>   #include  <sys/stat.h>   #include  <fcntl.h>    #include  <assert.h>   int main  ()    {        int keyboard;       int ret,i;        char c;       fd_set readfd;        struct timeval timeout;       keyboard = open ("/ Dev/tty ", O_rdonly | o_nonblock);       assert (keyboard>0);        while (1)        {            timeout.tv_sec=1;            Timeout.tv_usec=0;           fd_zero (&AMP;READFD);            fd_set (KEYBOARD,&AMP;READFD);               ///monitoring function            ret=select ( Keyboard+1,&readfd,null,null,&timeout);           if ( RET&NBSP;==&NBSP;-1)    //Error situation                 cout<< "Error" <<endl ;            else if (ret)     //return value greater than 0  data arrival                 if (Fd_isset (KEYBOARD,&AMP;READFD))                 {             &Nbsp;      i=read (keyboard,&c,1);                    if (' \ n ' ==c)                         continue ;                    printf ("hehethe input is %c\n", c);                    if  (' Q ' ==c)                         break;               }            else    //Timeout             {               cout<< "Time out" < <endl;               continue;            }       }  }   





This article has borrowed a lot of articles, expressed thanks:

http://blog.csdn.net/s_k_yliu/article/details/6642645

Http://blog.chinaunix.net/uid-26851094-id-3175153.html

Http://baike.baidu.com/view/3421856.htm

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.