Network Programming in UNIX: I/O multiplexing (2)

Source: Internet
Author: User
Tags htons

Select Function

This function allows the process to instruct the kernel to wait for any one of multiple events and wake up only when one or more events occur or wait for a specified period of time. We call select to inform the kernel of the descriptive words (reading, writing, or exception conditions) that are interested and how long the kernel will wait. The descriptive words we are interested in are not limited to a set of interfaces. You can use select to test any descriptive words.

Select function prototype:

 
# Include <sys/Select. H>
# Include <sys/time. h>
Int Select(IntMaxfd, fd_set * readset, fd_set * writeset, fd_set * exceptionset,Const StructTimeval * timeout );
Return: the positive number of ready descriptors,0-- Timeout ,-1-- Error

Parameter description of the select function: maxfd indicates the description to be tested.NumberThe value should be the maximum descriptive word + 1, The readset, writeset in the middle, and predictionset specify the descriptive words for the kernel test read, write, and exception conditions, the last parameter tells the kernel how long it takes to wait for any of the specified descriptions to be ready.

Timeval structure:

 
StructTimeval {
LongTV _sec;//Seconds
LongTV _usec;//Microseconds
}

The timeval parameter has three possible values: 1. null: It indicates waiting forever, which is equivalent to full blocking. 2. A fixed value indicates waiting for a fixed period of time. 3. The value of timeval is 0, indicating that the system does not wait. The system returns immediately after the description is checked, that is, the task is not blocked.

Fd_set structure:

The fd_set structure indicates a descriptive word set. It is typically represented by an integer array. Each digit of each integer corresponds to a descriptive word. Fd_set has the following four macros:

 Void Fd_zero (fd_set * fdset ); /*  Clear all bits in fdset */ 
Void Fd_set ( Int FD, fd_set * fdset ); /* Turn on the bit for FD in fdset */
Void Fd_clr ( Int FD, fd_set * fdset ); /* Turn off the bit for FD in fdset */
Int Fd_isset ( Int FD, fd_set * fdset );/* Is the bit for FD on in fdset? */

The select function modifies the description set pointed to by the readset, writeset, and predictionset pointers. Therefore, all three parameters are value-result parameters. That is, the values in the select function are modified during execution. When calling this function, we specify the value of the descriptive word of interest. When the function returns, the result indicates which descriptive words are ready. After this function is returned, we use fd_isset to test the description in the fd_set data type. When any bits in the description set corresponding to the not ready description word are returned, the return value is 0. therefore, every time we call the select function again, we have to set the concern position in all the descriptive word sets to 1. This is why we set the resset and allset sets in the Communication Example later.

The select function returns the condition that a set of interfaces are ready:

Communication Example of the select function: A simple TCP echo serverProgram

Selectserver. C: server programs using the select mechanism

 

 1 # Include <stdio. h>
2 # Include <String . H>
3 # Include <ARPA/inet. h>
4 # Include <netinet/ In . H>
5 # Include <sys/socket. h>
6 # Include <sys/ Select . H>
7
8 Const Static Int Maxline = 1024 ;
9 Const Static Int Serv_port = 10001 ;
10
11 Int Main1 ()
12 {
13 Int I, Maxi, maxfd, listenfd, connfd, sockfd;
14 /* Number of nready Descriptors */
15 Int Nready, client [fd_setsize];
16 Int N;
17 /* Create a descriptive word set. Because the select function clears the descriptive words that do not have an event, we set two sets. */
18 Fd_set rset, allset;
19 Char Buf [maxline];
20 Socklen_t clilen;
21 Struct Sockaddr_in cliaddr, servaddr;
22 /* Create socket */
23 Listenfd = socket (af_inet, sock_stream, 0 );
24 /* Define sockaddr_in */
25 Memset (& servaddr, 0 , Sizeof (Servaddr ));
26 Servaddr. sin_family = af_inet;
27 Servaddr. sin_port = htons (serv_port );
28 Servaddr. sin_addr.s_addr = htonl (inaddr_any );
29
30 BIND (listenfd ,(Struct Sockaddr *) & servaddr, Sizeof (Servaddr ));
31 Listen (listenfd, 100 );
32 /* Listenfd is the first descriptive word. */
33 /* The largest description, used as the first parameter of the select function. */
34 Maxfd = listenfd;
35 /* Number of clients used for polling */
36 Maxi =- 1 ;
37 /* Init */
38 For (I = 0 ; I <fd_setsize; I ++)
39 Client [I] =-1 ;
40 Fd_zero (& allset );
41 Fd_set (listenfd, & allset );
42
43 For (;;)
44 {
45 Rset = allset;
46 /* Only select the description word used for reading, blocking without timeout */
47 Nready = Select (Maxfd + 1 , & Rset, null );
48 If (Fd_isset (listenfd, & rset ))
49 {
50 Clilen = Sizeof (Cliaddr );
51 Connfd = accept (listenfd ,( Struct Sockaddr *) & cliaddr, & clilen );
52 /* Find the first location where new descriptive words can be placed */
53 For (I = 0 ; I <fd_setsize; I ++)
54 {
55 If (Client [I] < 0 )
56 {
57 Client [I] = connfd;
58 Break ;
59 }
60 }
61 /* The client is full. */
62 If (I = fd_setsize)
63 {
64 Printf ( " Too route clients, over stack. \ n " );
65 Return - 1 ;
66 }
67 Fd_set (connfd, & allset ); // Set FD
68 /* Update related parameters */
69 If (Connfd> maxfd) maxfd = connfd;
70 If (I> Maxi) maxi = I;
71 If (Nready <= 1 ) Continue ;
72 Else Nready --;
73 }
74
75 For (I = 0 ; I <= Maxi; I ++)
76 {
77 If (Client [I] < 0 ) Continue ;
78 Sockfd = client [I];
79 If (Fd_isset (sockfd, & rset ))
80 {
81 N = read (sockfd, Buf, maxline );
82 If (N = 0 )
83 {
84 /* When the other party closes, the server closes the description and clears the set sockfd. */
85 Close (sockfd );
86 Fd_clr (sockfd, & allset );
87 Client [I] =- 1 ;
88 }
89 Else
90 {
91 Buf [N] = ' \ 0 ' ;
92 Printf ( " Socket % d said: % s \ n " , Sockfd, Buf );
93 Write (sockfd, Buf, N ); // Write back to client
94 }
95 Nready --;
96 If (Nready <=0 ) Break ;
97 }
98 }
99
100 }
101 Return 0 ;
102 }


Client. C: simple client program

 1 # Include <stdio. h>
2 # Include < String . H>
3 # Include <ARPA/inet. h>
4 # Include <netinet/ In . H>
5 # Include <sys/socket. h>
6
7 # Define Maxline 1024
8 Int Main ()
9 {
10 Int Sockfd, N;
11 Char Buf [maxline];
12 Sockfd = socket (af_inet, sock_stream, 0 );
13 Struct Sockaddr_in servaddr;
14 Memset (& servaddr, 0 , Sizeof (Servaddr ));
15 Servaddr. sin_family = af_inet;
16 Servaddr. sin_port = htons ( 10001 );
17 Inet_ton (af_inet, " 127.0.0.1 " , & Servaddr. sin_addr );
18
19 Connect (sockfd ,( Struct Sockaddr *) & servaddr, Sizeof (Servaddr ));
20 While ( 1 )
21 {
22 Printf ( " Type some words... \ n " );
23 Scanf ( " % S " , Buf );
24 Write (sockfd, Buf, Sizeof (BUF ));
25 N = read (sockfd, Buf, maxline );
26 Printf ( " % D bytes encoded ed \ n " , N );
27 Buf [N] = ' \ 0 ' ;
28 Printf ( " % S \ n " , Buf );
29 }
30 Close (sockfd );
31 Return 0 ;
32 }


Summary:

In this article, we introduce the content of the select function in I/O multiplexing, and provide an example of a typical TCP reflection program, you can use select to handle the concurrency requirements of multiple clients. In the next Article , we will focus on the use of another common I/O reusable function poll.

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.