zoukankan      html  css  js  c++  java
  • IO多路复用之select总结

    1、基本概念

      IO多路复用是指内核一旦发现进程指定的一个或者多个IO条件准备读取,它就通知该进程。IO多路复用适用如下场合:

      (1)当客户处理多个描述字时(一般是交互式输入和网络套接口),必须使用I/O复用。

      (2)当一个客户同时处理多个套接口时,而这种情况是可能的,但很少出现。

      (3)如果一个TCP服务器既要处理监听套接口,又要处理已连接套接口,一般也要用到I/O复用。

      (4)如果一个服务器即要处理TCP,又要处理UDP,一般要使用I/O复用。

      (5)如果一个服务器要处理多个服务或多个协议,一般要使用I/O复用。

      与多进程和多线程技术相比,I/O多路复用技术的最大优势是系统开销小,系统不必创建进程/线程,也不必维护这些进程/线程,从而大大减小了系统的开销。

    2、select函数

      该函数准许进程指示内核等待多个事件中的任何一个发送,并只在有一个或多个事件发生或经历一段指定的时间后才唤醒。函数原型如下:

    #include <sys/select.h>
    #include <sys/time.h>
    
    int select(int maxfdp1,fd_set *readset,fd_set *writeset,fd_set *exceptset,const struct timeval *timeout)
    返回值:就绪描述符的数目,超时返回0,出错返回-1
    

    函数参数介绍如下:

    (1)第一个参数maxfdp1指定待测试的描述字个数,它的值是待测试的最大描述字加1(因此把该参数命名为maxfdp1),描述字0、1、2...maxfdp1-1均将被测试。

    因为文件描述符是从0开始的。

    (2)中间的三个参数readset、writeset和exceptset指定我们要让内核测试读、写和异常条件的描述字。如果对某一个的条件不感兴趣,就可以把它设为空指针。struct fd_set可以理解为一个集合,这个集合中存放的是文件描述符,可通过以下四个宏进行设置:

              void FD_ZERO(fd_set *fdset);           //清空集合

              void FD_SET(int fd, fd_set *fdset);   //将一个给定的文件描述符加入集合之中

              void FD_CLR(int fd, fd_set *fdset);   //将一个给定的文件描述符从集合中删除

              int FD_ISSET(int fd, fd_set *fdset);   // 检查集合中指定的文件描述符是否可以读写 

    (3)timeout告知内核等待所指定描述字中的任何一个就绪可花多少时间。其timeval结构用于指定这段时间的秒数和微秒数。

             struct timeval{

                       long tv_sec;   //seconds

                       long tv_usec;  //microseconds

           };

    这个参数有三种可能:

    (1)永远等待下去:仅在有一个描述字准备好I/O时才返回。为此,把该参数设置为空指针NULL。

    (2)等待一段固定时间:在有一个描述字准备好I/O时返回,但是不超过由该参数所指向的timeval结构中指定的秒数和微秒数。

    (3)根本不等待:检查描述字后立即返回,这称为轮询。为此,该参数必须指向一个timeval结构,而且其中的定时器值必须为0。

     原理图:

    3、测试程序

      写一个TCP回射程序,程序的功能是:客户端向服务器发送信息,服务器接收并原样发送给客户端,客户端显示出接收到的信息。

    服务端程序如下所示:

     1 #include <stdio.h>
      2 #include <stdlib.h>
      3 #include <string.h>
      4 #include <errno.h>
      5 #include <netinet/in.h>
      6 #include <sys/socket.h>
      7 #include <sys/select.h>
      8 #include <sys/types.h>
      9 #include <netinet/in.h>
     10 #include <arpa/inet.h>
     11 #include <unistd.h>
     12 #include <assert.h>
     13 
     14 #define IPADDR      "127.0.0.1"
     15 #define PORT        8787
     16 #define MAXLINE     1024
     17 #define LISTENQ     5
     18 #define SIZE        10
     19 
     20 
     21 typedef struct server_context_st
     22 {
     23     int cli_cnt;        /*客户端个数*/
     24     int clifds[SIZE];   /*客户端的个数*/
     25     fd_set allfds;      /*句柄集合*/
     26     int maxfd;          /*句柄最大值*/
     27 } server_context_st;
     28 
     29 
     30 static server_context_st *s_srv_ctx = NULL;
     31 
     32 
     33 /*===========================================================================
     34  * ==========================================================================*/
     35 static int create_server_proc(const char* ip,int port)
     36 {
     37     int  fd;
     38     struct sockaddr_in servaddr;
     39     fd = socket(AF_INET, SOCK_STREAM,0);
     40     if (fd == -1) {
     41         fprintf(stderr, "create socket fail,erron:%d,reason:%s
    ",
     42                 errno, strerror(errno));
     43         return -1;
     44     }
     45 
     46     int yes = 1;
     47     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {  
     48         return -1;
     49     }
     50 
     51     int reuse = 1;
     52     if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) == -1) {
     53         return -1;
     54     }
     55 
     56     bzero(&servaddr,sizeof(servaddr));
     57     servaddr.sin_family = AF_INET;
     58     inet_pton(AF_INET,ip,&servaddr.sin_addr);
     59     servaddr.sin_port = htons(port);
     60 
     61     if (bind(fd,(struct sockaddr*)&servaddr,sizeof(servaddr)) == -1) {
     62         perror("bind error: ");
     63         return -1;
     64     }
     65 
     66     listen(fd,LISTENQ);
     67 
     68     return fd;
     69 }
     70 
     71 static int accept_client_proc(int srvfd)
     72 {
     73     struct sockaddr_in cliaddr;
     74     socklen_t cliaddrlen;
     75     cliaddrlen = sizeof(cliaddr);
     76     int clifd = -1;
     77 
     78     printf("accpet clint proc is called.
    ");
     79 
     80 ACCEPT:
     81     clifd = accept(srvfd,(struct sockaddr*)&cliaddr,&cliaddrlen);
     82 
     83     if (clifd == -1) {
     84         if (errno == EINTR) {
     85             goto ACCEPT;
     86         } else {
     87             fprintf(stderr, "accept fail,error:%s
    ", strerror(errno));
     88             return -1;
     89         }
     90     }
     91 
     92     fprintf(stdout, "accept a new client: %s:%d
    ",
     93                    inet_ntoa(cliaddr.sin_addr),cliaddr.sin_port);
     94 
     95     //将新的连接描述符添加到数组中
     96     int i = 0;
     97     for (i = 0; i < SIZE; i++) {
     98         if (s_srv_ctx->clifds[i] < 0) {
     99             s_srv_ctx->clifds[i] = clifd;
    100             s_srv_ctx->cli_cnt++;
    101             break;
    102         }
    103     }
    104 
    105     if (i == SIZE) {
    106         fprintf(stderr,"too many clients.
    ");
    107         return -1;
    108     }
    109 
    110 }
    111 
    112 static int handle_client_msg(int fd, char *buf) 
    113 {
    114     assert(buf);
    115 
    116     printf("recv buf is :%s
    ", buf);
    117 
    118     write(fd, buf, strlen(buf) +1);
    119 
    120     return 0;
    121 }
    122 
    123 static void recv_client_msg(fd_set *readfds)
    124 {
    125     int i = 0, n = 0;
    126     int clifd;
    127     char buf[MAXLINE] = {0};
    128     for (i = 0;i <= s_srv_ctx->cli_cnt;i++) {
    129         clifd = s_srv_ctx->clifds[i];
    130         if (clifd < 0) {
    131             continue;
    132         }
    133 
    134         if (FD_ISSET(clifd, readfds)) {
    135             //接收客户端发送的信息
    136             n = read(clifd, buf, MAXLINE);
    137             if (n <= 0) {
    138                 FD_CLR(clifd, &s_srv_ctx->allfds);
    139                 close(clifd);
    140                 s_srv_ctx->clifds[i] = -1;
    141                 continue;
    142             }
    143 
    144             handle_client_msg(clifd, buf);
    145         }
    146     }
    147 }
    148 static void handle_client_proc(int srvfd)
    149 {
    150     int  clifd = -1;
    151     int  retval = 0;
    152     fd_set *readfds = &s_srv_ctx->allfds;
    153     struct timeval tv;
    154     int i = 0;
    155 
    156     while (1) {
    157 
    158         /*每次调用select前都要重新设置文件描述符和时间,因为事件发生后,文件描述符和时间都被内核修改啦*/
    159         /*添加监听套接字*/
    160         FD_ZERO(readfds);
    161         FD_SET(srvfd, readfds);
    162         s_srv_ctx->maxfd = srvfd;
    163 
    164         tv.tv_sec = 30;
    165         tv.tv_usec = 0;
    166 
    167         /*添加客户端套接字*/
    168         for (i = 0; i < s_srv_ctx->cli_cnt; i++) {
    169             clifd = s_srv_ctx->clifds[i];
    170             FD_SET(clifd, readfds);
    171             s_srv_ctx->maxfd = (clifd > s_srv_ctx->maxfd ? clifd : s_srv_ctx->maxfd);
    172         }
    173 
    174         retval = select(s_srv_ctx->maxfd + 1, readfds, NULL, NULL, &tv);
    175 
    176         if (retval == -1) {
    177             fprintf(stderr, "select error:%s.
    ", strerror(errno));
    178             return;
    179         }
    180 
    181         if (retval == 0) {
    182             fprintf(stdout, "select is timeout.
    ");
    183             continue;
    184         }
    185 
    186         if (FD_ISSET(srvfd, readfds)) {
    187             /*监听客户端请求*/
    188             accept_client_proc(srvfd);
    189         } else {
    190             /*接受处理客户端消息*/
    191             recv_client_msg(readfds);
    192         }
    193     }
    194 }
    195 
    196 
    197 static void server_uninit()
    198 {
    199     if (s_srv_ctx) {
    200         free(s_srv_ctx);
    201         s_srv_ctx = NULL;
    202     }
    203 }
    204 
    205 static int server_init()
    206 {
    207     s_srv_ctx = (server_context_st *)malloc(sizeof(server_context_st));
    208     if (s_srv_ctx == NULL) {
    209         return -1;
    210     }
    211 
    212     memset(s_srv_ctx, 0, sizeof(server_context_st));
    213 
    214     int i = 0;
    215     for (;i < SIZE; i++) {
    216         s_srv_ctx->clifds[i] = -1;
    217     }
    218 
    219     return 0;
    220 }
    221 
    222 int main(int argc,char *argv[])
    223 {
    224     int  srvfd;
    225 
    226     if (server_init() < 0) {
    227         return -1;
    228     }
    229 
    230     srvfd = create_server_proc(IPADDR, PORT);
    231     if (srvfd < 0) {
    232         fprintf(stderr, "socket create or bind fail.
    ");
    233         goto err;
    234     }
    235 
    236     handle_client_proc(srvfd);
    237 
    238     return 0;
    239 
    240 err:
    241     server_uninit();
    242     return -1;
    

    客户端程序如下:

     1 #include <netinet/in.h>
     2 #include <sys/socket.h>
     3 #include <stdio.h>
     4 #include <string.h>
     5 #include <stdlib.h>
     6 #include <sys/select.h>
     7 #include <time.h>
     8 #include <unistd.h>
     9 #include <sys/types.h>
    10 #include <errno.h>
    11 
    12 #define MAXLINE 1024
    13 #define IPADDRESS "127.0.0.1"
    14 #define SERV_PORT 8787
    15 
    16 #define max(a,b) (a > b) ? a : b
    17 
    18 static void handle_recv_msg(int sockfd, char *buf) 
    19 {
    20 printf("client recv msg is:%s
    ", buf);
    21 sleep(5);
    22 write(sockfd, buf, strlen(buf) +1);
    23 }
    24 
    25 static void handle_connection(int sockfd)
    26 {
    27 char sendline[MAXLINE],recvline[MAXLINE];
    28 int maxfdp,stdineof;
    29 fd_set readfds;
    30 int n;
    31 struct timeval tv;
    32 int retval = 0;
    33 
    34 while (1) {
    35 
    36 FD_ZERO(&readfds);
    37 FD_SET(sockfd,&readfds);
    38 maxfdp = sockfd;
    39 
    40 tv.tv_sec = 5;
    41 tv.tv_usec = 0;
    42 
    43 retval = select(maxfdp+1,&readfds,NULL,NULL,&tv);
    44 
    45 if (retval == -1) {
    46 return ;
    47 }
    48 
    49 if (retval == 0) {
    50 printf("client timeout.
    ");
    51 continue;
    52 }
    53 
    54 if (FD_ISSET(sockfd, &readfds)) {
    55 n = read(sockfd,recvline,MAXLINE);
    56 if (n <= 0) {
    57 fprintf(stderr,"client: server is closed.
    ");
    58 close(sockfd);
    59 FD_CLR(sockfd,&readfds);
    60 return;
    61 }
    62 
    63 handle_recv_msg(sockfd, recvline);
    64 }
    65 }
    66 }
    67 
    68 int main(int argc,char *argv[])
    69 {
    70 int sockfd;
    71 struct sockaddr_in servaddr;
    72 
    73 sockfd = socket(AF_INET,SOCK_STREAM,0);
    74 
    75 bzero(&servaddr,sizeof(servaddr));
    76 servaddr.sin_family = AF_INET;
    77 servaddr.sin_port = htons(SERV_PORT);
    78 inet_pton(AF_INET,IPADDRESS,&servaddr.sin_addr);
    79 
    80 int retval = 0;
    81 retval = connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
    82 if (retval < 0) {
    83 fprintf(stderr, "connect fail,error:%s
    ", strerror(errno));
    84 return -1;
    85 }
    86 
    87 printf("client send to server .
    ");
    88 write(sockfd, "hello server", 32);
    89 
    90 handle_connection(sockfd);
    91 
    92 return 0;
    93 }
    

    4、程序结果

      启动服务程序,执行三个个客户程序进行测试,结果如下图所示:

    参考:

    http://konglingchun.is-programmer.com/posts/12146.html

    http://blog.163.com/smileface100@126/blog/static/27720874200951024532966/

  • 相关阅读:
    Sort it
    set 集合容器
    convertToString与ToString的区别
    string基本字符系列容器
    辗转相除法
    进程的总结
    进程池进阶
    进程池
    生产者消费者模型
    IPC :进程之间的通信
  • 原文地址:https://www.cnblogs.com/alan-babyblog/p/5393433.html
Copyright © 2011-2022 走看看