Socket programming Select (), poll (), Epoll ()

Source: Internet
Author: User
Tags epoll

Socket programming, communication

Client socket ()----->connect ()------->recv ()-----> Close ();

Server-side sockets ()----->bind ()------> Listen ()---->accept ()------>send ()------->close ();

1> socket (int family,int type,int protocol);

Family, protocol type

Af_inet--------------> IPV4

Af_inet6---------------> IPV6

Af_route---------------> Routing Socket Interface

Type-> refers to a socket type

Sock_stream--------------------> Byte throttle socket TCP

Sock_dgram--------------------> Datagram sockets UDP

Sock_raw--------------------> Raw sockets

The function call successfully returns a small nonnegative integer, the file descriptor type, otherwise 1 indicates that the call failed

2.connect (int sockfd,struct sockaddr*addr,socklen_t Addrlen)

SOCKFD is the return value from the socket;

Addr is a pointer to the address structure of the server's socket

Addrlen is the size of the address structure of the socket

1 structsockaddr_in server;2Bzero (&server,sizeof(server));3server.sin_family =af_inet;4Server.sin_port = htonl (1234);5SERVER.SIN_ADDR.S_ADDR = Inte_addr ("127.0.0.1");6 if(Connect (SOCKFD,structSOCKADDR *) &server,sizeof(server)) == -1)7 {8     //mandatory address translation to universal socket structure9}

3>bind (int sockfd,struct sockaddr *server,socklen_len addrlen);

return value of Sockfd->socket

Server-> a pointer to an address structure that points to a specific protocol

Addrlen-> indicates the length of the address structure of the socket

1 structsockaddr_in server;2Bzero (&server,sizeof(server));3server.sin_family =af_inet;4Server.sin_port = htonl (1234);5SERVER.SIN_ADDR.S_ADDR =htonl (inaddr_any);6 if(Bind (SOCKFD, (structSOCKADDR *) &server,sizeof(server)) == -1)7 {8     ///SOCKADDR Cast9}

4>listen (int sockfd,int backlog)

SOCKFD--->socket return value

The backlog---> specifies the maximum number of connections that the request returns to the queue, which limits the number of pending service requests in the queue, and if the input queue is full when a service request arrives, the socket rejects the connection request.

Listen (sockfd,5);

For a listening socket, the kernel maintains two queues: The connection queue is not completed and the connection queue is completed

Connection queue not completed: An entry for the SYN section that establishes a connection for each request, the server is waiting to complete three handshake, the current socket is in the SYN_RECD state

Completed connection queue: Opens an entry for each client that completes the TCP three handshake, established the current socket state.

5>accept (int sockfd,struct sockaddr *client,socklen_t *addrlen)

SOCKFD is the socket descriptor returned by the socket (), which becomes a listening socket when calling listen

Client is the socket and address structure that returns each other

Addrlen is the length of the corresponding structure

The ACCETP () function returns, the socket descriptor is connected.

Note:

A server can have only one listener socket, and will persist until the server shuts down, but the connection socket descriptor is the kernel for each accepted customer to create one, when the server completes the data transfer with the customer, to close the connection socket, so the listener socket accepts the customer's link request, The connected socket descriptor is responsible for data transfer to the customer.

1 intLISTENFD,CONNFD;2 structsockaddr_in client;3 socklen_t Addrlen;4Addrlen =sizeof(client);5CONNFD = Accept (LISTENFD, (structSOCKADDR *) &client,&Addrlen);6 if(CONNFD = =-1)7 {8     9}

The prototype is as follows:

1 int Select (int maxfdp, fd_set *readfds, Fd_set *writefds, fd_set *errorfds, const struct timeval *timeout);


Each parameter has the following meanings:

    • int MAXFDP: Maximum descriptor value + 1
    • Fd_set *readfds: A set of descriptors that are interesting to read
    • Fd_set *writefds: A set of descriptors that are interested in writing
    • Fd_set *errorfds: Set of descriptors interested in errors
    • struct Timeval *timeout: timeout (note: For Linux systems, this parameter does not have a const limit, the value of timeout is modified to the remaining time for each select call and the UNIX system does not change the timeout value)

The Select function returns when the following conditions occur:

    1. Readfds descriptor-readable in the collection
    2. Writefds Descriptor writable in collection
    3. Errorfds encountered an error condition in the collection
    4. The specified time-out timeout was reached.

When select returns, the Descriptor collection is modified to indicate which descriptors are in a readable, writable, or Error state. You can test the descriptor with the Fd_isset macro to find the descriptor for the state change. If select is returned because of a timeout, all descriptor sets will be emptied.
The Select function returns the total number of descriptors for which the state has changed. Returning 0 means a timeout. Failure returns 1 and sets the errno. Possible errors are: EBADF (invalid descriptor), EINTR (returned by the terminal), EINVAL (Nfds or timeout value error).
The set Descriptor collection is usually defined with several macros:

 1  Fd_zero (fd_set *fdset); /*   set all bits to 0  */         2  fd_set (int  FD, Fd_set *fdset); /*   set the FD bit to 1  */         3  fd_clr (int  FD, Fd_set *fdset); /*   set the FD bit to 0  */ 4  int  fd, Fd_set *fdset); /*   detects if the FD bit is 1  */ 

Such as:

1 Fd_set set;2Fd_zero (&rset);/*I initialize RSet*/3Fd_set (1, &rset);/*The description of FD = 1 is subscript character to 1*/4Fd_set (4, &rset);/*The description of FD = 4 is subscript character to 1*/5Fd_set (5, &rset);/*The description of FD = 5 is subscript character to 1*/

When select returns, the RSet bits are set to 0, except for those with the changed FD bit.
is considered to be readable when the following conditions occur:

    1. The number of bytes in the receive buffer of the socket is greater than the Low-water Mark property value of the socket's receive buffer. (The Low-water mark value is similar to a watershed, and when the number of bytes in receive buffer is less than the Low-water mark value, the socket is considered unreadable, only if the receive The socket is considered readable only when the number of bytes in the buffer reaches a certain amount
    2. Connection semi-closed (read off, i.e. receive the fin packets from the end)
    3. A change in the descriptor is a passive socket, while the number of connected three-way handshake completion is greater than 0, that is, a new TCP connection is established
    4. The descriptor has an error, and returns 1 if the call to the read system calls the reading socket.

is considered writable when the following happens:

    1. The number of bytes in the socket's send buffer is greater than the Low-water Mark property value of the socket's send buffer and the socket is connected or does not require a connection (such as UDP).
    2. Write half connection closed, calling the Write function will produce sigpipe
    3. The descriptor has an error, and 1 is returned if the write system is called to call the socket.

Attention:
The number of descriptors that can be processed by the select default is capped, which is the size of the fd_setsize.
For the timeout parameter, if NULL is set, the wait forever is indicated, and if timeout->tv_sec = timeout->tv_usec = 0, then do not wait for at all, otherwise specify the waiting time.
If you use Select to handle multiple sockets, you need to use an array (or other structure) to record the state of each descriptor. The use of poll is not required, see below poll function.

(ii) poll () function

The prototype is as follows:

1 int poll (struct POLLFD *fdarray, unsigned long nfds, int timeout);


Each parameter has the following meanings:

    • struct POLLFD *fdarray: A struct that holds the relevant state of each descriptor.
    • The size of the unsigned long Nfds:fdarray array, which contains the number of valid members.
    • int timeout: Sets the time-out period. (in milliseconds)

Poll function return value and meaning are as follows:

    • -1: Error generated
    • 0: Timeout time to, and no description have status change
    • >0: Number of descriptors with state changes

Focus on the Fdarray array, because this is where it differs from the Select () function mainly:
The structure of the POLLFD is as follows:

1  struct POLLFD {2     int fd;                  /* Test Descriptor */ 3      short events;      /* Test Conditions */ 4      short revents;     /*  */5 };


In fact, the poll () and select () functions have the same problem to deal with, except that they are being rolled out at almost the same time by different organizations, so they are preserved at the same time. The Select () function puts the readable descriptor, the writable descriptor, and the error descriptor in three sets, all three of which are marked with a bit bit, and once a number of descriptor states have changed, then it will be set, while the bits of the other descriptor that have not changed will be clear, That is, the Readset, Writeset, and Errorset of select () are a value-result type, passing values through them, and returning the results through them. One disadvantage of this is that the collection must be re-assigned each time the select is re-evaluated. The poll () function, in contrast to select (), holds the state of each descriptor through an array of structures, with each struct having the first FD representing the descriptor, the second representing the event to be listened to, the event of interest, and the third item representing the return state of the descriptor when the poll () returns. The legal status is as follows:

    • Pollin: Regular data or priority data is readable
    • Pollrdnorm: Plain Data readable
    • Pollrdband: have priority data readable
    • Pollpri: There is an urgent data to read
    • Pollout: There are general data to write
    • Pollwrnorm: There are general data to write
    • Pollwrband: There is emergency data to write
    • Pollerr: An error has occurred
    • Pollhup: A descriptor hangs event occurs
    • Pollnval: Descriptor illegal

For Pollin | Pollpri equivalent to the readable event of select (); Pollout | Pollwrband equivalent to writable events of select (); Pollin Equivalence and Pollrdnorm | Pollrdband, while pollout is equivalent to Pollwrband. If you are interested in events such as readable events and writable events and errors for a descriptor then you should set them accordingly.
The settings for timeout are as follows:

      • Inftim:wait Forever
      • 0:return immediately, do not block
      • >0:wait specified number of milliseconds

Socket programming Select (), poll (), Epoll ()

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.