Select, poll, Epoll usage

Source: Internet
Author: User
Tags epoll htons

We start with the famous c10k problem, because the early in the network is not popular, the internet is not a lot of users, a server at the same time online 100 users estimate at that time is already considered a large application. However, with the development of the Internet and the rapid expansion of user groups, every user must maintain a TCP connection with the server in order to make real-time data interaction. Web sites such as Facebook may have billions of concurrent TCP connections at the same time. That's when the problem comes.

There are two main ways to solve this problem: one is to allocate a separate process or thread for each connection processing, and the other is to process several connections simultaneously using the same process or thread.

The first solution, which is to have a TCP link, is to allocate a process/thread. And the process is the most expensive resources of the operating system, a machine can not create many processes, such as c10k problems to create 10,000 processes, the operating system is unbearable.

The second solution, that is, each process/thread handles multiple connections simultaneously (IO multiplexing), the Select,poll,epoll we discuss is based on this idea.

  1. The simplest way to do this is to cycle through each request, each connected to a socket, when all the sockets have data, this method is feasible, but when the application read a socket file data is not ready, The entire application blocks here to wait for the file handle, even if the other file handle is ready and cannot be processed down.
  2. Select to solve is the above blocking problem, the idea is very simple, if I read the file handle before the first view of its state, ready to be processed, not ready will not be processed, so that the problem solved.
    1. Select uses the fd_set struct to tell the kernel to monitor multiple file handles simultaneously, and the call returns when there is a change or timeout in the state of the file handle. Then use Fd_isset to catch a view of which file handle has changed.
    2. Fd_set can be understood as a collection, this collection is stored in the file descriptor (the file descriptor), that is, the document 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 that a socket is a file, the socket handle is a file descriptor.
    3. Fd_set collections can be manipulated by a number of macros, Fd_zero (fd_set*): Emptying the Set, fd_set (int, fd_set*): Adding the specified file descriptor to the collection; fd_clr (int, fd_set*) : Removes a given file descriptor from the collection; fd_isset (int, fd_set*): Determines whether the specified file descriptor can be read or written.
    4. Select function Prototype: int select (int maxfdp,fd_set *readfds,fd_set *writefds,fd_set *errorfds,struct timeval *timeout);
      1. MAXFDP: The range of all file descriptors in the collection, that is, the maximum value of all file descriptors +1;
      2. Readfds: Specifies the set of file descriptors we want to monitor for read changes, that is, whether we can read data from these files;
      3. Writefds: Specifies the set of file descriptors we want to monitor for write changes, that is, whether we can write data from these files;
      4. Errorfds: Used to monitor file error exceptions;
      5. Timeout:select Timeout, if this parameter is set to NULL, indicates blocking until a file descriptor state changes, if this parameter is set to 0 seconds 0 milliseconds, indicating non-blocking, direct return, and a return value of 0 means that no file descriptor has changed, A return value of 0 indicates that a file descriptor has changed, if this parameter is set to greater than 0, indicates the time of the wait, if an event occurs, returns a value other than 0, if there has been no event, wait for this parameter to set the time, and then return 0.
    5. Select Example:
      1. SERVER.C:
        #include <sys/time.h>#include<netinet/inch.h>#include<sys/Select.h>#include<sys/types.h>#include<sys/socket.h>#include<unistd.h>#include<stdio.h>#include<stdlib.h>intMain () {intSocket1, Socket2; structsockaddr_in socket1addr, socket2addr;    Fd_set FDS; structTimeval Timeout = {3,0}; Charbuffer[ the] = {0}; Socket1= Socket (pf_inet, SOCK_DGRAM,0); //bzero (&socket1addr, sizeof (SOCKET1ADDR));socket1addr.sin_family =af_inet; Socket1addr.sin_addr.s_addr=htonl (Inaddr_any); Socket1addr.sin_port= Htons (36500); Bind (Socket1, (structsockaddr*) &socket1addr,sizeof(SOCKET1ADDR)); Socket2= Socket (pf_inet, SOCK_DGRAM,0); //bzero (&socket2addr, sizeof (SOCKET2ADDR));socket2addr.sin_family =af_inet; Socket2addr.sin_addr.s_addr=htonl (Inaddr_any); Socket2addr.sin_port= Htons (36501); Bind (Socket2, (structsockaddr*) &socket2addr,sizeof(SOCKET2ADDR));  while(1) {Fd_zero (&FDS); Fd_set (Socket1,&FDS); Fd_set (Socket2,&FDS); intMAXFDP = (Socket1 > Socket2)? (socket1+1): (Socket2 +1); intretval =Select(MAXFDP, &fds, NULL, NULL, &timeout); if(RetVal = =-1) {printf ("error\n"); return-1; }Else if(RetVal = =0){            Continue; }Else{            structsockaddr_in Client; intLen =sizeof(client); if(Fd_isset (Socket1, &FDS)) {recvfrom (socket1, buffer, the,0, (structsockaddr*) &client, &Len); printf ("%u says:%s\n", Ntohs (client.sin_port), buffer); }            if(Fd_isset (Socket2, &FDS)) {recvfrom (Socket2, buffer, the,0, (structsockaddr*) &client, &Len); printf ("%u says:%s\n", Ntohs (client.sin_port), buffer); }        }            }}
        View Code
      2. Client.c
        #include <stdio.h>#include<string.h>#include<sys/socket.h>#include<netinet/inch.h>intMainintargcChar**argv) {    if(ARGC <2) {printf ("Usage:%s port\n", argv[0]); return-1; }    intSOCKFD; structsockaddr_in servaddr; SOCKFD= Socket (pf_inet, SOCK_DGRAM,0); Bzero (&AMP;SERVADDR,sizeof(SERVADDR)); Servaddr.sin_family=af_inet; Servaddr.sin_port= Htons (Atoi (argv[1])); Servaddr.sin_addr.s_addr= Inet_addr ("127.0.0.1"); Charsendline[ -]; sprintf (Sendline,"Hello, world!."); SendTo (SOCKFD, Sendline, strlen (sendline),0, (structSOCKADDR *) &servaddr,sizeof(SERVADDR));    Close (SOCKFD); return 1;}
        View Code

Select, poll, Epoll usage

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.