Select of multiplexing I/O model

Source: Internet
Author: User

1 . The so-called I/O multiplexing means that the kernel notifies the process when it discovers that one or more I/O conditions specified by the process are ready to be read. I/O multiplexing is suitable for the following occasions:

(1) When a client processes multiple descriptors (typically interactive input and network socket interfaces), I/O multiplexing must be used.

(2) When a client handles multiple sets of interfaces at the same time, this is possible, but rarely occurs.

(3) If a TCP server handles both the listener socket and the connected sleeve interface, I/O multiplexing is generally used.

(4) If a server is to handle TCP, but also to handle UDP, generally use I/O multiplexing.

(5) If a server is to handle multiple services or multiple protocols, I/O multiplexing is generally used.

2 . In the context of multiple I/O multiplexing, applications need to handle multiple input streams and output streams at the same time, and if we use blocking patterns, we do not achieve the desired goal; If you use non-blocking mode, polling multiple inputs will waste CPU time; If you use multiple processes/ Multithreading to handle such problems will make the program more complex and difficult to maintain, so the best way is to use "multiple I/O multiplexing."

3 . Select function
This function allows the process to instruct the kernel to wait for any one of the events to occur, and to wake only after one or more times occur or after a specified amount of time;
The function prototype is:

int select (int Nfds, 
            fd_set *readfds, 
            fd_set *writefds, 
            fd_set *exceptfds, 
            struct timeval);

Required headers:/
 * According to POSIX.1-2001 * * *
   #include <sys/select.h>/
 * According to earlier standards */< c8/> #include <sys/time.h>
  #include <sys/types.h>
  #include <unistd.h>

Function Description:
The Select () function waits for a change in the state of a file descriptor. The parameter Nfds represents the largest file descriptor +1, Readfds, Writefds, and Execptfds are called "descriptor groups" to return the descriptor's read, write, or abnormal condition;

Meaning of each parameter in select:

Nfds: Represents the highest number of file descriptors to be checked in the collection +1
Readfds: Collection of read file descriptors that are monitored by the Select () function
Writefds: Collection of write-file descriptors that are monitored by the Select () function
Execptfds: Collection of exception handling file descriptors monitored by the Select () function
Timeout
For timeout, it is a structure pointer, the prototype is: struct timeval *timeout; the precision of this time structure can be set to the delicate level. The structure is as follows:

struct Timeval *timeout{
    long tv_sec;    /* Second seconds *
    /long tv_unsec;  /* and microseconds microseconds */
}

There are 3 types of variable settings for this structure:

1.
NULL: means "always wait". Until the signal is captured or the file descriptor is ready
. If a signal is captured, the Select returns -1,errno
set to Eintr
2.
Timeout->tv_sec = = 0 && timeout->tv_usec = 0;
Indicates "No waiting at all"; tests all specified descriptors and returns immediately. This is the
polling method that gets the state of multiple descriptors without blocking the Select function;
3.
Timeout->tv_sec!= 0 && timeout->tv_usec!= 0;
Represents "waits for the specified number of seconds and microseconds." Returns immediately when one of the specified descriptors (Readfds
, Writefds, or Execptfds) is ready, or when the specified time value is
exceeded. If no file descriptor is ready at timeout, the
return value is 0;

A select function is a blocking function that when the SELECT function returns, that is, when a file descriptor can read and write data, the read-write function can be used to read and write the data, and its return value indicates how many files have a message; compared to blocking mode, The high point of multiplexing is the ability to wait for multiple file descriptors at the same time, and the Select function can return when any one of those file descriptors enters a ready state.

Conclusion: The Select function is a "blocking" function, and when the function is executed, there must be one of the following 2 events;
1.select monitored file I/O collection, there is a message in the file
2. Time timed out, specifying the timeout by using the 5th parameter of select

4. When using the Select function, the file descriptor needs to be sorted, and when the file descriptor is processed, 4 macro functions are involved, respectively:

                Select File descriptor set process macros/

* Clear a collection of file descriptors
/Fd_zero (fd_set *set)/ 

* Add a file descriptor to the collection of file descriptors
/fd_set (int FD, fd_set *set) 

/* Remove a file descriptor from the collection of file descriptors
/fd_clr (int fd, fd_set *set)/

* Test If a file descriptor in the collection has not sent changes
/fd_isset (int fd , Fd_set *set)

Typically, before using the Select function, you should first invoke Fd_zero and Fd_set
to initialize the set of file descriptors, which can be recycled when you use the Select function f_ Isset to test which file descriptor is ready and, after executing the relevant file descriptor
, you can use FD_CLR to clear the file descriptor.

5. The principle of the Select function is:

Select the FD with data from the set set, and once the file descriptor in the set set sends a state change, select immediately exits the blocking state and then continues to perform the appropriate action.

6. Example 1
Linux under the/dev/input/has a mice mouse read and write event files and event1 keyboard read and write event files, when opened with open these two files, and read the operation, is a blocking operation, that is, when the keyboard keys are pressed, or the mouse is clicked, Will unblock, start reading and writing; now use select I/O multiplexing model knowledge to solve this problem, with a process (main program) to deal with, when there is a keyboard read and write, immediately to call a keyboard printing function, if the mouse read and write, immediately execute the mouse print function;

There are two places to note:
(1)  You need to modify the permissions of the two files/dev/input/mice and/dev/input/event1
(2) where  you print the mouse response event and the keyboard response event, Every time you take the
value out of the set, otherwise, every time you judge the data inside, you get caught in a dead loop;

results: When a mouse is pressed, print "The mouse is answered ..."; When a keyboard is
pressed, print "The keyboard is answered ...";
/************************************************************************* * File name:select.c * author:the Answer * Function:other * mail:2412799512@qq.com * Created time:2017 year June 16 Friday 16:14 19 seconds **************** /#include <stdio.h> #include <stdlib.h> # include<string.h> #include <sys/types.h> #include <errno.h> #include <sys/stat.h> #include <fcntl.h> #include <signal.h> #include <time.h> #include <unistd.h> void sys_err (const char *PTR
    , int num) {perror (PTR);
Exit (NUM);
    int main (int argc,char **argv) {int fd_mice = open ("/dev/input/mice", o_rdonly);

    if (Fd_mice < 0) Sys_err ("Open Mice",-1);
    int fd_key = open ("/dev/input/event1", o_rdonly);

    if (Fd_key < 0) Sys_err ("Open Keyboard",-2);
        while (1) {struct Timeval timeout;
        Fd_set set;
        int maxfd; /* Remove the maximum of two file descriptorsWHO/maxfd = fd_mice > Fd_key?
        Fd_mice:fd_key;
        /* Initialization Set Set */Fd_zero (&set);
        * * Add the corresponding description set to the Set set/Fd_set (Fd_mice,&set);

        Fd_set (Fd_key, &set);  
        /* Set Select block wait maximum time (seconds)/timeout.tv_sec = 5;
  timeout.tv_usec = 0;
        /* Select has a ready file descriptor to return, otherwise wait * 5 seconds after the error * */INT ret = SELECT (Maxfd + 1,&set,null,null,&timeout);
            if (ret = 0) {printf ("Time out\n");
            Continue
            Indicates that the signal is interrupted by}else if (ret = 1 && errno = = eintr) {printf ("Signal inturrupt\n");
        Continue
            }else if (ret = 1) {printf ("Bad error\n");
        Break
            }else if (Ret > 0) {char buf[1024];

            /* Bzero will buf the sizeof (BUF) byte space in all 0 */bzero (buf,sizeof (BUF));

    if (Fd_isset (Fd_key,&set)) {printf ("Keyboard has message ... \ n");            * Remember to read the data, otherwise it will die cycle/Read (fd_key,buf,sizeof (BUF));

                } if (Fd_isset (Fd_mice,&set)) {puts ("mouse has message ... \ n");
            * Remember to read the data, otherwise it will die cycle/Read (fd_mice,buf,sizeof (BUF));

 }
        }
    }
}

Example 2:

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.