Linux中select IO复用机制

本文详细介绍了多路复用技术select的工作原理及其在实际编程中的应用。通过讲解select函数的基本概念、参数含义和返回值,帮助读者理解如何利用select进行高效的文件描述符状态监测。同时,给出了具体的示例代码,演示如何使用select处理网络连接和监听。
转载自:http://blog.youkuaiyun.com/tianmohust/article/details/6595998

函数作用:

系统提供select函数来实现多路复用输入/输出模型。select系统调用是用来让我们的程序监视多个文件句柄的状态变化的。程序会停在select这里等待,直到被监视的文件句柄有一个或多个发生了状态改变。关于文件句柄,其实就是一个整数,我们最熟悉的句柄是0、1、2三个,0是标准输入,1是标准输出,2是标准错误输出。0、1、2是整数表示的,对应的FILE *结构的表示就是stdin、stdout、stderr。

int select(int maxfdp,fd_set *readfds,fd_set *writefds,fd_set *errorfds,struct timeval *timeout);
 
/*参数列表
int maxfdp是一个整数值,是指集合中所有文件描述符的范围,即所有文件描述符的最大值加1,不能错!在Windows中这个参数的值无所谓,可以设置不正确。 
  
fd_set *readfds是指向fd_set结构的指针,这个集合中应该包括文件描述符,我们是要监视这些文件描述符的读变化的,即我们关心是否可以从这些文件中读取数据了,如果这个集合中有一个文件可读,select就会返回一个大于0的值,表示有文件可读,如果没有可读的文件,则根据timeout参数再判断是否超时,若超出timeout的时间,select返回0,若发生错误返回负值。可以传入NULL值,表示不关心任何文件的读变化。 
  
fd_set *writefds是指向fd_set结构的指针,这个集合中应该包括文件描述符,我们是要监视这些文件描述符的写变化的,即我们关心是否可以向这些文件中写入数据了,如果这个集合中有一个文件可写,select就会返回一个大于0的值,表示有文件可写,如果没有可写的文件,则根据timeout参数再判断是否超时,若超出timeout的时间,select返回0,若发生错误返回负值。可以传入NULL值,表示不关心任何文件的写变化。 
  
fd_set *errorfds同上面两个参数的意图,用来监视文件错误异常。 
  
struct timeval* timeout是select的超时时间,这个参数至关重要,它可以使select处于三种状态:
第一,若将NULL以形参传入,即不传入时间结构,就是将select置于阻塞状态,一定等到监视文件描述符集合中某个文件描述符发生变化为止;
第二,若将时间值设为0秒0毫秒,就变成一个纯粹的非阻塞函数,不管文件描述符是否有变化,都立刻返回继续执行,文件无变化返回0,有变化返回一个正值;
第三,timeout的值大于0,这就是等待的超时时间,即 select在timeout时间内阻塞,超时时间之内有事件到来就返回了,否则在超时后不管怎样一定返回,返回值同上述。
*/

/*
返回值: 

负值:select错误

正值:某些文件可读写或出错

0:等待超时,没有可读写或错误的文件
*/

函数原型:

  1. int select(int maxfd,fd_set *rdset,fd_set *wrset, \  
  2.            fd_set *exset,struct timeval *timeout);  
int select(int maxfd,fd_set *rdset,fd_set *wrset, \
		   fd_set *exset,struct timeval *timeout);

参数说明:

参数maxfd是需要监视的最大的文件描述符值+1;rdset,wrset,exset分别对应于需要检测的可读文件描述符的集合,可写文件描述符的集 合及异常文件描述符的集合。struct timeval结构用于描述一段时间长度,如果在这个时间内,需要监视的描述符没有事件发生则函数返回,返回值为0。

下面的宏提供了处理这三种描述词组的方式:
FD_CLR(inr fd,fd_set* set);用来清除描述词组set中相关fd 的位
FD_ISSET(int fd,fd_set *set);用来测试描述词组set中相关fd 的位是否为真
FD_SET(int fd,fd_set*set);用来设置描述词组set中相关fd的位
FD_ZERO(fd_set *set);用来清除描述词组set的全部位

参数timeout为结构timeval,用来设置select()的等待时间,其结构定义如下:

  1. struct timeval  
  2. {  
  3.     time_t tv_sec;//second  
  4.     time_t tv_usec;//minisecond  
  5. };  
struct timeval
{
	time_t tv_sec;//second
    time_t tv_usec;//minisecond
};

如果参数timeout设为:

NULL,则表示select()没有timeout,select将一直被阻塞,直到某个文件描述符上发生了事件。

0:仅检测描述符集合的状态,然后立即返回,并不等待外部事件的发生。

特定的时间值:如果在指定的时间段里没有事件发生,select将超时返回。

函数返回值:

执行成功则返回文件描述词状态已改变的个数,如果返回0代表在描述词状态改变前已超过timeout时间,没有返回;当有错误发生时则返回-1,错误原因存于errno,此时参数readfds,writefds,exceptfds和timeout的值变成不可预测。错误值可能为:
EBADF 文件描述词为无效的或该文件已关闭
EINTR 此调用被信号所中断
EINVAL 参数n 为负值。
ENOMEM 核心内存不足

常见的程序片段如下:

fs_set readset;
FD_ZERO(&readset);
FD_SET(fd,&readset);
select(fd+1,&readset,NULL,NULL,NULL);
if(FD_ISSET(fd,readset){……}

理解select模型:

理解select模型的关键在于理解fd_set,为说明方便,取fd_set长度为1字节,fd_set中的每一bit可以对应一个文件描述符fd。则1字节长的fd_set最大可以对应8个fd。

(1)执行fd_set set; FD_ZERO(&set);则set用位表示是0000,0000。

(2)若fd=5,执行FD_SET(fd,&set);后set变为0001,0000(第5位置为1)

(3)若再加入fd=2,fd=1,则set变为0001,0011

(4)执行select(6,&set,0,0,0)阻塞等待

(5)若fd=1,fd=2上都发生可读事件,则select返回,此时set变为0000,0011。注意:没有事件发生的fd=5被清空。

 基于上面的讨论,可以轻松得出select模型的特点:

  (1)可监控的文件描述符个数取决与sizeof(fd_set)的值。我这边服务 器上sizeof(fd_set)=512,每bit表示一个文件描述符,则我服务器上支持的最大文件描述符是512*8=4096。据说可调,另有说虽 然可调,但调整上限受于编译内核时的变量值。本人对调整fd_set的大小不太感兴趣,参考http://www.cppblog.com /CppExplore/archive/2008/03/21/45061.html中的模型2(1)可以有效突破select可监控的文件描述符上 限。

  (2)将fd加入select监控集的同时,还要再使用一个数据结构array保存放到select监控集中的fd,一是用于再select 返回后,array作为源数据和fd_set进行FD_ISSET判断。二是select返回后会把以前加入的但并无事件发生的fd清空,则每次开始 select前都要重新从array取得fd逐一加入(FD_ZERO最先),扫描array的同时取得fd最大值maxfd,用于select的第一个 参数。

  (3)可见select模型必须在select前循环array(加fd,取maxfd),select返回后循环array(FD_ISSET判断是否有时间发生)。

下面给一个伪码说明基本select模型的服务器模型:

  1. nSock=0;  
  2. array[nSock++]=listen_fd;(之前listen port已绑定并listen)  
  3. maxfd=listen_fd;  
  4.   
  5. while(1){  
  6.   
  7.  FD_ZERO(&set);  
  8.   
  9.  foreach (fd in array)  
  10.  {  
  11.   fd大于maxfd,则maxfd=fd  
  12.   FD_SET(fd,&set)  
  13.  }  
  14.   
  15.  res=select(maxfd+1,&set,0,0,0);  
  16.   
  17.  if(FD_ISSET(listen_fd,&set))  
  18.  {  
  19.   newfd=accept(listen_fd);  
  20.   array[nsock++]=newfd;  
  21.   if(--res<=0) continue;  
  22.  }  
  23.   
  24.  foreach 下标1开始 (fd in array)  
  25.  {  
  26.   if(FD_ISSET(fd,&tyle="COLOR: #ff0000">set))  
  27.   执行读等相关操作  
  28.   如果错误或者关闭,则要删除该fd,将array中相应位置和最后一个元素互换就好,nsock减一  
  29.   if(--res<=0) continue;  
  30.  }  
  31.   
  32. }  
	
  nSock=0;
  array[nSock++]=listen_fd;(之前listen port已绑定并listen)
  maxfd=listen_fd;

  while(1){

	  FD_ZERO(&set);

	  foreach (fd in array)
	  {
		  fd大于maxfd,则maxfd=fd
		  FD_SET(fd,&set)
	  }

	  res=select(maxfd+1,&set,0,0,0);

	  if(FD_ISSET(listen_fd,&set))
	  {
		  newfd=accept(listen_fd);
		  array[nsock++]=newfd;
		  if(--res<=0) continue;
	  }

	  foreach 下标1开始 (fd in array)
	  {
		  if(FD_ISSET(fd,&tyle="COLOR: #ff0000">set))
		  执行读等相关操作
		  如果错误或者关闭,则要删除该fd,将array中相应位置和最后一个元素互换就好,nsock减一
		  if(--res<=0) continue;
	  }

  }
检测键盘有无输入,完整的程序如下:

  1. #include<sys/time.h>  
  2. #include<sys/types.h>  
  3. #include<unistd.h>  
  4. #include<string.h>  
  5. #include<stdlib.h>  
  6. #include<stdio.h>  
  7. int main()  
  8. {  
  9.         char buf[10]="";  
  10.         fd_set rdfds;  
  11.         struct timeval tv;  
  12.         int ret;  
  13.         FD_ZERO(&rdfds);  
  14.         FD_SET(0,&rdfds);   //文件描述符0表示stdin键盘输入  
  15.         tv.tv_sec = 3;  
  16.         tv.tv_usec = 500;  
  17.         ret = select(1,&rdfds,NULL,NULL,&tv);  
  18.         if(ret<0)  
  19.               printf("\n selcet");  
  20.         else if(ret == 0)  
  21.               printf("\n timeout");  
  22.         else  
  23.               printf("\n ret = %d",ret);  
  24.   
  25.         if(FD_ISSET(1,&rdfds))  //如果有输入,从stdin中获取输入字符  
  26.         {  
  27.               printf("\n reading");  
  28.               fread(buf,9,1,stdin);  
  29.          }  
  30.          write(1,buf,strlen(buf));  
  31.          printf("\n %d \n",strlen(buf));  
  32.          return 0;  
  33. }  
  34. //执行结果ret = 1.  
#include<sys/time.h>
#include<sys/types.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
int main()
{
        char buf[10]="";
        fd_set rdfds;
        struct timeval tv;
        int ret;
        FD_ZERO(&rdfds);
        FD_SET(0,&rdfds);   //文件描述符0表示stdin键盘输入
        tv.tv_sec = 3;
        tv.tv_usec = 500;
        ret = select(1,&rdfds,NULL,NULL,&tv);
        if(ret<0)
              printf("\n selcet");
        else if(ret == 0)
              printf("\n timeout");
        else
              printf("\n ret = %d",ret);

        if(FD_ISSET(1,&rdfds))  //如果有输入,从stdin中获取输入字符
        {
              printf("\n reading");
              fread(buf,9,1,stdin);
         }
         write(1,buf,strlen(buf));
         printf("\n %d \n",strlen(buf));
         return 0;
}
//执行结果ret = 1.

利用Select模型,设计的web服务器:

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <unistd.h>  
  4. #include <errno.h>  
  5. #include <string.h>  
  6. #include <sys/types.h>  
  7. #include <sys/socket.h>  
  8. #include <netinet/in.h>  
  9. #include <arpa/inet.h>  
  10.   
  11. #define MYPORT 88960    // the port users will be connecting to  
  12.   
  13. #define BACKLOG 10     // how many pending connections queue will hold  
  14.   
  15. #define BUF_SIZE 200  
  16.   
  17. int fd_A[BACKLOG];    // accepted connection fd  
  18. int conn_amount;    // current connection amount  
  19.   
  20. void showclient()  
  21. {  
  22.     int i;  
  23.     printf("client amount: %d\n", conn_amount);  
  24.     for (i = 0; i < BACKLOG; i++) {  
  25.         printf("[%d]:%d  ", i, fd_A[i]);  
  26.     }  
  27.     printf("\n\n");  
  28. }  
  29.   
  30. int main(void)  
  31. {  
  32.     int sock_fd, new_fd;  // listen on sock_fd, new connection on new_fd  
  33.     struct sockaddr_in server_addr;    // server address information  
  34.     struct sockaddr_in client_addr; // connector's address information  
  35.     socklen_t sin_size;  
  36.     int yes = 1;  
  37.     char buf[BUF_SIZE];  
  38.     int ret;  
  39.     int i;  
  40.   
  41.     if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {  
  42.         perror("socket");  
  43.         exit(1);  
  44.     }  
  45.   
  46.     if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {  
  47.         perror("setsockopt");  
  48.         exit(1);  
  49.     }  
  50.       
  51.     server_addr.sin_family = AF_INET;         // host byte order  
  52.     server_addr.sin_port = htons(MYPORT);     // short, network byte order  
  53.     server_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP  
  54.     memset(server_addr.sin_zero, '\0'sizeof(server_addr.sin_zero));  
  55.   
  56.     if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {  
  57.         perror("bind");  
  58.         exit(1);  
  59.     }  
  60.   
  61.     if (listen(sock_fd, BACKLOG) == -1) {  
  62.         perror("listen");  
  63.         exit(1);  
  64.     }  
  65.   
  66.     printf("listen port %d\n", MYPORT);  
  67.   
  68.     fd_set fdsr;  
  69.     int maxsock;  
  70.     struct timeval tv;  
  71.   
  72.     conn_amount = 0;  
  73.     sin_size = sizeof(client_addr);  
  74.     maxsock = sock_fd;  
  75.     while (1) {  
  76.         // initialize file descriptor set  
  77.         FD_ZERO(&fdsr);  
  78.         FD_SET(sock_fd, &fdsr);  
  79.   
  80.         // timeout setting  
  81.         tv.tv_sec = 30;  
  82.         tv.tv_usec = 0;  
  83.   
  84.         // add active connection to fd set  
  85.         for (i = 0; i < BACKLOG; i++) {  
  86.             if (fd_A[i] != 0) {  
  87.                 FD_SET(fd_A[i], &fdsr);  
  88.             }  
  89.         }  
  90.   
  91.         ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv);  
  92.         if (ret < 0) {  
  93.             perror("select");  
  94.             break;  
  95.         } else if (ret == 0) {  
  96.             printf("timeout\n");  
  97.             continue;  
  98.         }  
  99.   
  100.         // check every fd in the set  
  101.         for (i = 0; i < conn_amount; i++) {  
  102.             if (FD_ISSET(fd_A[i], &fdsr)) {  
  103.                 ret = recv(fd_A[i], buf, sizeof(buf), 0);  
  104.                   
  105.                 char str[] = "Good,very nice!\n";  
  106.                   
  107.                 send(fd_A[i],str,sizeof(str) + 1, 0);  
  108.                   
  109.                   
  110.                 if (ret <= 0) {        // client close  
  111.                     printf("client[%d] close\n", i);  
  112.                     close(fd_A[i]);  
  113.                     FD_CLR(fd_A[i], &fdsr);  
  114.                     fd_A[i] = 0;  
  115.                 } else {        // receive data  
  116.                     if (ret < BUF_SIZE)  
  117.                         memset(&buf[ret], '\0', 1);  
  118.                     printf("client[%d] send:%s\n", i, buf);  
  119.                 }  
  120.             }  
  121.         }  
  122.   
  123.         // check whether a new connection comes  
  124.         if (FD_ISSET(sock_fd, &fdsr)) {  
  125.             new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);  
  126.             if (new_fd <= 0) {  
  127.                 perror("accept");  
  128.                 continue;  
  129.             }  
  130.   
  131.             // add to fd queue  
  132.             if (conn_amount < BACKLOG) {  
  133.                 fd_A[conn_amount++] = new_fd;  
  134.                 printf("new connection client[%d] %s:%d\n", conn_amount,  
  135.                         inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));  
  136.                 if (new_fd > maxsock)  
  137.                     maxsock = new_fd;  
  138.             }  
  139.             else {  
  140.                 printf("max connections arrive, exit\n");  
  141.                 send(new_fd, "bye", 4, 0);  
  142.                 close(new_fd);  
  143.                 break;  
  144.             }  
  145.         }  
  146.         showclient();  
  147.     }  
  148.   
  149.     // close other connections  
  150.     for (i = 0; i < BACKLOG; i++) {  
  151.         if (fd_A[i] != 0) {  
  152.             close(fd_A[i]);  
  153.         }  
  154.     }  
  155.   
  156.     exit(0);  
  157. }  
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define MYPORT 88960    // the port users will be connecting to

#define BACKLOG 10     // how many pending connections queue will hold

#define BUF_SIZE 200

int fd_A[BACKLOG];    // accepted connection fd
int conn_amount;    // current connection amount

void showclient()
{
    int i;
    printf("client amount: %d\n", conn_amount);
    for (i = 0; i < BACKLOG; i++) {
        printf("[%d]:%d  ", i, fd_A[i]);
    }
    printf("\n\n");
}

int main(void)
{
    int sock_fd, new_fd;  // listen on sock_fd, new connection on new_fd
    struct sockaddr_in server_addr;    // server address information
    struct sockaddr_in client_addr; // connector's address information
    socklen_t sin_size;
    int yes = 1;
    char buf[BUF_SIZE];
    int ret;
    int i;

    if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        perror("socket");
        exit(1);
    }

    if (setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
        perror("setsockopt");
        exit(1);
    }
    
    server_addr.sin_family = AF_INET;         // host byte order
    server_addr.sin_port = htons(MYPORT);     // short, network byte order
    server_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
    memset(server_addr.sin_zero, '\0', sizeof(server_addr.sin_zero));

    if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
        perror("bind");
        exit(1);
    }

    if (listen(sock_fd, BACKLOG) == -1) {
        perror("listen");
        exit(1);
    }

    printf("listen port %d\n", MYPORT);

    fd_set fdsr;
    int maxsock;
    struct timeval tv;

    conn_amount = 0;
    sin_size = sizeof(client_addr);
    maxsock = sock_fd;
    while (1) {
        // initialize file descriptor set
        FD_ZERO(&fdsr);
        FD_SET(sock_fd, &fdsr);

        // timeout setting
        tv.tv_sec = 30;
        tv.tv_usec = 0;

        // add active connection to fd set
        for (i = 0; i < BACKLOG; i++) {
            if (fd_A[i] != 0) {
                FD_SET(fd_A[i], &fdsr);
            }
        }

        ret = select(maxsock + 1, &fdsr, NULL, NULL, &tv);
        if (ret < 0) {
            perror("select");
            break;
        } else if (ret == 0) {
            printf("timeout\n");
            continue;
        }

        // check every fd in the set
        for (i = 0; i < conn_amount; i++) {
            if (FD_ISSET(fd_A[i], &fdsr)) {
                ret = recv(fd_A[i], buf, sizeof(buf), 0);
				
				char str[] = "Good,very nice!\n";
				
				send(fd_A[i],str,sizeof(str) + 1, 0);
				
				
                if (ret <= 0) {        // client close
                    printf("client[%d] close\n", i);
                    close(fd_A[i]);
                    FD_CLR(fd_A[i], &fdsr);
                    fd_A[i] = 0;
                } else {        // receive data
                    if (ret < BUF_SIZE)
                        memset(&buf[ret], '\0', 1);
                    printf("client[%d] send:%s\n", i, buf);
                }
            }
        }

        // check whether a new connection comes
        if (FD_ISSET(sock_fd, &fdsr)) {
            new_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &sin_size);
            if (new_fd <= 0) {
                perror("accept");
                continue;
            }

            // add to fd queue
            if (conn_amount < BACKLOG) {
                fd_A[conn_amount++] = new_fd;
                printf("new connection client[%d] %s:%d\n", conn_amount,
                        inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
                if (new_fd > maxsock)
                    maxsock = new_fd;
            }
            else {
                printf("max connections arrive, exit\n");
                send(new_fd, "bye", 4, 0);
                close(new_fd);
                break;
            }
        }
        showclient();
    }

    // close other connections
    for (i = 0; i < BACKLOG; i++) {
        if (fd_A[i] != 0) {
            close(fd_A[i]);
        }
    }

    exit(0);
}
补充部分:

1 基本原理

Resize icon

注:select 原理图,摘自 IBM iSeries 信息中心

1 数据结构与函数原型

1.1 select

  • 函数原型
       int select(
          int nfds,
          fd_set *readset,
          fd_set *writeset,
          fd_set* exceptset,
          struct timeval *timeout
       );
    
  • 头文件
    • select位于:
      #include <sys/select.h>
      
    • struct timeval位于:
      #include <sys/time.h>
      
  • 返回值

    返回对应位仍然为1的fd的总数。

  • 参数
    • nfds:第一个参数是:最大的文件描述符值+1;
    • readset:可读描述符集合;
    • writeset:可写描述符集合;
    • exceptset:异常描述符;
    • timeout:select 的监听时长,如果这短时间内所监听的 socket 没有事件发生。

1.2 fd_set

1.2.1 清空描述符集合
FD_ZERO(fd_set *)
1.2.2 向描述符集合添加指定描述符
FD_SET(int, fd_set *)
1.2.3 从描述符集合删除指定描述符
FD_CLR(int, fd_set *)
1.2.4 检测指定描述符是否在描述符集合中
FD_ISSET(int, fd_set *)
1.2.5 描述符最大数量
#define FD_SETSIZE 1024

1.3 描述符集合

可读描述符集合中可读的描述符,为1,其他为0;可写也类似。异常描述符集合中有异常等待处理的描述符的值为1,其他为0。

1.4 ioctl

  • 函数原型:

      int ioctl(int handle, int cmd,[int *argdx, int argcx]);
    
  • 头文件:

      #include <sys/ioctl.h>
    
  • 返回值:

    • 0 - 成功
    • 1 - 失败

2 示例

程序各部分的解释在注释中。

#include <sys/socket.h>
#include <string.h>
#include <sys/time.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>

#define TRUE  1
#define FALSE 0

int main(int argc, char *argv[])
{
    int i, len, rc, on = TRUE;
    int listen_sd, new_sd = 0, max_sd;
    int desc_ready;
    char buffer[80];
    int close_conn, end_server = FALSE;
    struct sockaddr_in server_addr;
    struct timeval timeout;
    struct fd_set master_set, working_set;

    // Listen
    listen_sd = socket(AF_INET, SOCK_STREAM, 0);
    if (listen_sd < 0)
    {
        perror("socket() failed");
        exit(-1);
    }

    // Set socket options
    rc = setsockopt(listen_sd, SOL_SOCKET, SO_REUSEADDR, (char *) &on, sizeof(on));
    if (rc < 0)
    {
        perror("setsockopt() failed");
        close(listen_sd);
        exit(-1);
    }

    // Set IO control
    rc = ioctl(listen_sd, FIONBIO, (char *) &on);
    if (rc < 0)
    {
        perror("ioctl() failed");
        close(listen_sd);
        exit(-1);
    }

    // Bind
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(atoi(argv[1]));
    rc = bind(listen_sd, (struct sockaddr *) &server_addr, sizeof(server_addr));
    if (rc < 0)
    {
        perror("bind() failed\n");
        close(listen_sd);
        exit(-1);
    }

    // Listen
    rc = listen(listen_sd, 32);
    if (rc < 0)
    {
        perror("listen() failed\n");
        close(listen_sd);
        exit(-1);
    }

    // Intialize sd set
    FD_ZERO(&master_set);
    max_sd = listen_sd;
    FD_SET(listen_sd, &master_set);

    timeout.tv_sec = 3 * 60;
    timeout.tv_usec = 0;

    // Start
    do
    {
        // Copy master_set into working_set
        memcpy(&working_set, &master_set, sizeof(master_set));

        printf("Waiting on select()...\n");
        rc = select(max_sd + 1, &working_set, NULL, NULL, &timeout);
        if (rc < 0)
        {
            perror("  select() failed\n");
            break;
        }
        if (rc == 0)
        {
            printf("  select() timed out. End program.\n");
            break;
        }

        desc_ready = rc; // number of sds ready in working_set

        // Check each sd in working_set
        for (i = 0; i <= max_sd && desc_ready > 0; ++i)
        {
            // Check to see if this sd is ready
            if (FD_ISSET(i, &working_set))
            {
                --desc_ready;

                // Check to see if this is the listening sd
                if (i == listen_sd)
                {
                    printf("  Listeing socket is readable\n");
                    do
                    {
                        // Accept
                        new_sd = accept(listen_sd, NULL, NULL);

                        // Nothing to be accepted
                        if (new_sd < 0)
                        {
                            // All have been accepted
                            if (errno != EWOULDBLOCK)
                            {
                                perror("  accept() failed\n");
                                end_server = TRUE;
                            }
                            break;
                        }

                        // Insert new_sd into master_set
                        printf("  New incoming connection - %d\n", new_sd);
                        FD_SET(new_sd, &master_set);
                        if (new_sd > max_sd)
                        {
                            max_sd = new_sd;
                        }
                    }
                    while (new_sd != -1);
                }
                // This is not the listening sd
                else
                {
                    close_conn = FALSE;
                    printf("  Descriptor %d is avaliable\n", i);
                    do
                    {
                        rc = recv(i, buffer, sizeof(buffer), 0);

                        // Receive data on sd "i", until failure occurs
                        if (rc < 0)
                        {
                            // Normal failure
                            if (errno != EWOULDBLOCK)
                            {
                                perror("  recv() failed\n");
                                close_conn = TRUE;
                            }
                            break;
                        }

                        // The connection has been closed by the client
                        if (rc == 0)
                        {
                            printf("  Connection closed\n");
                            close_conn = TRUE;
                            break;
                        }

                        /* Receiving data succeeded and echo it back
                           the to client */
                        len = rc;
                        printf("  %d bytes received\n", len);
                        rc = send(i, buffer, len, 0);
                        if (rc < 0)
                        {
                            perror("  send() failed");
                            close_conn = TRUE;
                            break;
                        }
                    }
                    while (TRUE);

                    // If unknown failure occured
                    if (close_conn)
                    {
                        // Close the sd and remove it from master_set
                        close(i);
                        FD_CLR(i, &master_set);

                        // If this is the max sd
                        if (i == max_sd)
                        {
                            // Find the max sd in master_set now
                            while (FD_ISSET(max_sd, &master_set) == FALSE)
                            {
                                --max_sd;
                            }
                        } // End of if (i == max_sd)
                    } // End of if (close_conn)
                }
            }
        }
    }
    while (end_server == FALSE);

    /* Close each sd in master_set */
    for (i = 0; i < max_sd; ++i)
    {
        if (FD_ISSET(i, &master_set))
        {
            close(i);
        }
    }

    return 0;
}

关于select在异步(非阻塞)connect中的应用,  用select可以很好地解决这一问题.大致过程是这样的: 
1.将打开的socket设为非阻塞的,可以用fcntl(socket, F_SETFL, O_NDELAY)完 成(有的系统用FNEDLAY也可). 
2.发connect调用,这时返回-1,但是errno被设为EINPROGRESS,意即connect仍旧 在进行还没有完成. 

3.将打开的socket设进被监视的可写(注意不是可读)文件集合用select进行监视, 如果可写,用 getsockopt(socket, SOL_SOCKET, SO_ERROR, &error, sizeof(int)); 来得到error的值,如果为零,则connect成功. 

  1. /usr/include/asm/errno.h  
  2. #define EPERM 1 /* Operation not permitted */操作不允许  
  3.   #define ENOENT 2 /* No such file or directory */文件/路径不存在  
  4.   #define ESRCH 3 /* No such process */进程不存在  
  5.   #define EINTR 4 /* Interrupted system call */中断的系统调用  
  6.   #define EIO 5 /* I/O error */I/O错误  
  7.   #define ENXIO 6 /* No such device or address */设备/地址不存在  
  8.   #define E2BIG 7 /* Arg list too long */参数列表过长  
  9.   #define ENOEXEC 8 /* Exec format error */执行格式错误  
  10.   #define EBADF 9 /* Bad file number */错误文件编号  
  11.   #define ECHILD 10 /* No child processes */子进程不存在  
  12.   #define EAGAIN 11 /* Try again */重试  
  13.   #define ENOMEM 12 /* Out of memory */内存不足  
  14.   #define EACCES 13 /* Permission denied */无权限  
  15.   #define EFAULT 14 /* Bad address */地址错误  
  16.   #define ENOTBLK 15 /* Block device required */需要块设备  
  17.   #define EBUSY 16 /* Device or resource busy */设备或资源忙  
  18.   #define EEXIST 17 /* File exists */文件已存在  
  19.   #define EXDEV 18 /* Cross-device link */跨设备链路  
  20.   #define ENODEV 19 /* No such device */设备不存在  
  21.   #define ENOTDIR 20 /* Not a directory */路径不存在  
  22.   #define EISDIR 21 /* Is a directory */是路径  
  23.   #define EINVAL 22 /* Invalid argument */无效参数  
  24.   #define ENFILE 23 /* File table overflow */文件表溢出  
  25.   #define EMFILE 24 /* Too many open files */打开的文件过多  
  26.   #define ENOTTY 25 /* Not a typewriter */非打字机  
  27.   #define ETXTBSY 26 /* Text file busy */文本文件忙  
  28.   #define EFBIG 27 /* File too large */文件太大  
  29.   #define ENOSPC 28 /* No space left on device */设备无空间  
  30.   #define ESPIPE 29 /* Illegal seek */非法查询  
  31.   #define EROFS 30 /* Read-only file system */只读文件系统  
  32.   #define EMLINK 31 /* Too many links */链接太多  
  33.   #define EPIPE 32 /* Broken pipe */管道破裂  
  34.   #define EDOM 33 /* Math argument out of domain of func */参数超出函数域  
  35.   #define ERANGE 34 /* Math result not representable */结果无法表示  
  36.   #define EDEADLK 35 /* Resource deadlock would occur */资源将发生死锁  
  37.   #define ENAMETOOLONG 36 /* File name too long */文件名太长  
  38.   #define ENOLCK 37 /* No record locks available */没有可用的记录锁  
  39.   #define ENOSYS 38 /* Function not implemented */函数未实现  
  40.   #define ENOTEMPTY 39 /* Directory not empty */目录非空  
  41.   #define ELOOP 40 /* Too many symbolic links encountered */遇到太多符号链接  
  42.   #define EWOULDBLOCK EAGAIN /* Operation would block */操作会阻塞  
  43.   #define ENOMSG 42 /* No message of desired type */没有符合需求类型的消息  
  44.   #define EIDRM 43 /* Identifier removed */标识符已删除  
  45.   #define ECHRNG 44 /* Channel number out of range */通道编号超出范围  
  46.   #define EL2NSYNC 45 /* Level 2 not synchronized */level2不同步  
  47.   #define EL3HLT 46 /* Level 3 halted */3级停止  
  48.   #define EL3RST 47 /* Level 3 reset */3级重置  
  49.   #define ELNRNG 48 /* Link number out of range */链接编号超出范围  
  50.   #define EUNATCH 49 /* Protocol driver not attached */协议驱动程序没有连接  
  51.   #define ENOCSI 50 /* No CSI structure available */没有可用的CSI结构  
  52.   #define EL2HLT 51 /* Level 2 halted */2级停止  
  53.   #define EBADE 52 /* Invalid exchange */无效交换  
  54.   #define EBADR 53 /* Invalid request descriptor */无效请求描述  
  55.   #define EXFULL 54 /* Exchange full */交换完全  
  56.   #define ENOANO 55 /* No anode */无阳极  
  57.   #define EBADRQC 56 /* Invalid request code */无效请求码  
  58.   #define EBADSLT 57 /* Invalid slot */无效插槽  
  59.   #define EDEADLOCK EDEADLK  
  60.   #define EBFONT 59 /* Bad font file format */错误的字体文件格式  
  61.   #define ENOSTR 60 /* Device not a stream */设备不是流  
  62.   #define ENODATA 61 /* No data available */无数据  
  63.   #define ETIME 62 /* Timer expired */计时器到期  
  64.   #define ENOSR 63 /* Out of streams resources */流资源不足  
  65.   #define ENONET 64 /* Machine is not on the network */机器不在网络上  
  66.   #define ENOPKG 65 /* Package not installed */包未安装  
  67.   #define EREMOTE 66 /* Object is remote */对象是远程  
  68.   #define ENOLINK 67 /* Link has been severed */链接正在服务中  
  69.   #define EADV 68 /* Advertise error */广告错误  
  70.   #define ESRMNT 69 /* Srmount error */?  
  71.   #define ECOMM 70 /* Communication error on send */发送过程中通讯错误  
  72.   #define EPROTO 71 /* Protocol error */协议错误  
  73.   #define EMULTIHOP 72 /* Multihop attempted */多跳尝试  
  74.   #define EDOTDOT 73 /* RFS specific error */RFS特定错误  
  75.   #define EBADMSG 74 /* Not a data message */不是数据类型消息  
  76.   #define EOVERFLOW 75 /* Value too large for defined data type */对指定的数据类型来说值太大  
  77.   #define ENOTUNIQ 76 /* Name not unique on network */网络上名字不唯一  
  78.   #define EBADFD 77 /* File descriptor in bad state */文件描述符状态错误  
  79.   #define EREMCHG 78 /* Remote address changed */远程地址改变  
  80.   #define ELIBACC 79 /* Can not access a needed shared library */无法访问需要的共享库  
  81.   #define ELIBBAD 80 /* Accessing a corrupted shared library */访问损坏的共享库  
  82.   #define ELIBSCN 81 /* .lib section in a.out corrupted */库部分在a.out损坏  
  83.   #define ELIBMAX 82 /* Attempting to link in too many shared libraries */试图链接太多的共享库  
  84.   #define ELIBEXEC 83 /* Cannot exec a shared library directly */不能直接运行共享库  
  85.   #define EILSEQ 84 /* Illegal byte sequence */非法字节序  
  86.   #define ERESTART 85 /* Interrupted system call should be restarted */应重新启动被中断的系统调用  
  87.   #define ESTRPIPE 86 /* Streams pipe error */流管错误  
  88.   #define EUSERS 87 /* Too many users */用户太多  
  89.   #define ENOTSOCK 88 /* Socket operation on non-socket */在非套接字上进行套接字操作  
  90.   #define EDESTADDRREQ 89 /* Destination address required */需要目的地址  
  91.   #define EMSGSIZE 90 /* Message too long */消息太长  
  92.   #define EPROTOTYPE 91 /* Protocol wrong type for socket */错误协议类型  
  93.   #define ENOPROTOOPT 92 /* Protocol not available */协议不可用  
  94.   #define EPROTONOSUPPORT 93 /* Protocol not supported */不支持协议  
  95.   #define ESOCKTNOSUPPORT 94 /* Socket type not supported */不支持套接字类型  
  96.   #define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */操作上不支持传输端点  
  97.   #define EPFNOSUPPORT 96 /* Protocol family not supported */不支持协议族  
  98.   #define EAFNOSUPPORT 97 /* Address family not supported by protocol */协议不支持地址群  
  99.   #define EADDRINUSE 98 /* Address already in use */地址已被使用  
  100.   #define EADDRNOTAVAIL 99 /* Cannot assign requested address */无法分配请求的地址  
  101.   #define ENETDOWN 100 /* Network is down */网络已关闭  
  102.   #define ENETUNREACH 101 /* Network is unreachable */网络不可达  
  103.   #define ENETRESET 102 /* Network dropped connection because of reset */网络由于复位断开连接  
  104.   #define ECONNABORTED 103 /* Software caused connection abort */软件导致连接终止  
  105.   #define ECONNRESET 104 /* Connection reset by peer */连接被对方复位  
  106.   #define ENOBUFS 105 /* No buffer space available */没有可用的缓存空间  
  107.   #define EISCONN 106 /* Transport endpoint is already connected */传输端点已连接  
  108.   #define ENOTCONN 107 /* Transport endpoint is not connected */传输端点未连接  
  109.   #define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */传输端点关闭后不能在发送  
  110.   #define ETOOMANYREFS 109 /* Too many references: cannot splice */太多的引用:无法接合  
  111.   #define ETIMEDOUT 110 /* Connection timed out */连接超时  
  112.   #define ECONNREFUSED 111 /* Connection refused */连接被拒绝  
  113.   #define EHOSTDOWN 112 /* Host is down */主机已关闭  
  114.   #define EHOSTUNREACH 113 /* No route to host */无法路由到主机  
  115.   #define EALREADY 114 /* Operation already in progress */操作已在进程中  
  116.   #define EINPROGRESS 115 /* Operation now in progress */进程中正在进行的操作  
  117.   #define ESTALE 116 /* Stale NFS file handle */  
  118.   #define EUCLEAN 117 /* Structure needs cleaning */  
  119.   #define ENOTNAM 118 /* Not a XENIX named type file */  
  120.   #define ENAVAIL 119 /* No XENIX semaphores available */  
  121.   #define EISNAM 120 /* Is a named type file */  
  122.   #define EREMOTEIO 121 /* Remote I/O error */  
  123.   #define EDQUOT 122 /* Quota exceeded */  
  124.   #define ENOMEDIUM 123 /* No medium found */  
  125.   #define EMEDIUMTYPE 124 /* Wrong medium type */  
/usr/include/asm/errno.h
#define EPERM 1 /* Operation not permitted */操作不允许
  #define ENOENT 2 /* No such file or directory */文件/路径不存在
  #define ESRCH 3 /* No such process */进程不存在
  #define EINTR 4 /* Interrupted system call */中断的系统调用
  #define EIO 5 /* I/O error */I/O错误
  #define ENXIO 6 /* No such device or address */设备/地址不存在
  #define E2BIG 7 /* Arg list too long */参数列表过长
  #define ENOEXEC 8 /* Exec format error */执行格式错误
  #define EBADF 9 /* Bad file number */错误文件编号
  #define ECHILD 10 /* No child processes */子进程不存在
  #define EAGAIN 11 /* Try again */重试
  #define ENOMEM 12 /* Out of memory */内存不足
  #define EACCES 13 /* Permission denied */无权限
  #define EFAULT 14 /* Bad address */地址错误
  #define ENOTBLK 15 /* Block device required */需要块设备
  #define EBUSY 16 /* Device or resource busy */设备或资源忙
  #define EEXIST 17 /* File exists */文件已存在
  #define EXDEV 18 /* Cross-device link */跨设备链路
  #define ENODEV 19 /* No such device */设备不存在
  #define ENOTDIR 20 /* Not a directory */路径不存在
  #define EISDIR 21 /* Is a directory */是路径
  #define EINVAL 22 /* Invalid argument */无效参数
  #define ENFILE 23 /* File table overflow */文件表溢出
  #define EMFILE 24 /* Too many open files */打开的文件过多
  #define ENOTTY 25 /* Not a typewriter */非打字机
  #define ETXTBSY 26 /* Text file busy */文本文件忙
  #define EFBIG 27 /* File too large */文件太大
  #define ENOSPC 28 /* No space left on device */设备无空间
  #define ESPIPE 29 /* Illegal seek */非法查询
  #define EROFS 30 /* Read-only file system */只读文件系统
  #define EMLINK 31 /* Too many links */链接太多
  #define EPIPE 32 /* Broken pipe */管道破裂
  #define EDOM 33 /* Math argument out of domain of func */参数超出函数域
  #define ERANGE 34 /* Math result not representable */结果无法表示
  #define EDEADLK 35 /* Resource deadlock would occur */资源将发生死锁
  #define ENAMETOOLONG 36 /* File name too long */文件名太长
  #define ENOLCK 37 /* No record locks available */没有可用的记录锁
  #define ENOSYS 38 /* Function not implemented */函数未实现
  #define ENOTEMPTY 39 /* Directory not empty */目录非空
  #define ELOOP 40 /* Too many symbolic links encountered */遇到太多符号链接
  #define EWOULDBLOCK EAGAIN /* Operation would block */操作会阻塞
  #define ENOMSG 42 /* No message of desired type */没有符合需求类型的消息
  #define EIDRM 43 /* Identifier removed */标识符已删除
  #define ECHRNG 44 /* Channel number out of range */通道编号超出范围
  #define EL2NSYNC 45 /* Level 2 not synchronized */level2不同步
  #define EL3HLT 46 /* Level 3 halted */3级停止
  #define EL3RST 47 /* Level 3 reset */3级重置
  #define ELNRNG 48 /* Link number out of range */链接编号超出范围
  #define EUNATCH 49 /* Protocol driver not attached */协议驱动程序没有连接
  #define ENOCSI 50 /* No CSI structure available */没有可用的CSI结构
  #define EL2HLT 51 /* Level 2 halted */2级停止
  #define EBADE 52 /* Invalid exchange */无效交换
  #define EBADR 53 /* Invalid request descriptor */无效请求描述
  #define EXFULL 54 /* Exchange full */交换完全
  #define ENOANO 55 /* No anode */无阳极
  #define EBADRQC 56 /* Invalid request code */无效请求码
  #define EBADSLT 57 /* Invalid slot */无效插槽
  #define EDEADLOCK EDEADLK
  #define EBFONT 59 /* Bad font file format */错误的字体文件格式
  #define ENOSTR 60 /* Device not a stream */设备不是流
  #define ENODATA 61 /* No data available */无数据
  #define ETIME 62 /* Timer expired */计时器到期
  #define ENOSR 63 /* Out of streams resources */流资源不足
  #define ENONET 64 /* Machine is not on the network */机器不在网络上
  #define ENOPKG 65 /* Package not installed */包未安装
  #define EREMOTE 66 /* Object is remote */对象是远程
  #define ENOLINK 67 /* Link has been severed */链接正在服务中
  #define EADV 68 /* Advertise error */广告错误
  #define ESRMNT 69 /* Srmount error */?
  #define ECOMM 70 /* Communication error on send */发送过程中通讯错误
  #define EPROTO 71 /* Protocol error */协议错误
  #define EMULTIHOP 72 /* Multihop attempted */多跳尝试
  #define EDOTDOT 73 /* RFS specific error */RFS特定错误
  #define EBADMSG 74 /* Not a data message */不是数据类型消息
  #define EOVERFLOW 75 /* Value too large for defined data type */对指定的数据类型来说值太大
  #define ENOTUNIQ 76 /* Name not unique on network */网络上名字不唯一
  #define EBADFD 77 /* File descriptor in bad state */文件描述符状态错误
  #define EREMCHG 78 /* Remote address changed */远程地址改变
  #define ELIBACC 79 /* Can not access a needed shared library */无法访问需要的共享库
  #define ELIBBAD 80 /* Accessing a corrupted shared library */访问损坏的共享库
  #define ELIBSCN 81 /* .lib section in a.out corrupted */库部分在a.out损坏
  #define ELIBMAX 82 /* Attempting to link in too many shared libraries */试图链接太多的共享库
  #define ELIBEXEC 83 /* Cannot exec a shared library directly */不能直接运行共享库
  #define EILSEQ 84 /* Illegal byte sequence */非法字节序
  #define ERESTART 85 /* Interrupted system call should be restarted */应重新启动被中断的系统调用
  #define ESTRPIPE 86 /* Streams pipe error */流管错误
  #define EUSERS 87 /* Too many users */用户太多
  #define ENOTSOCK 88 /* Socket operation on non-socket */在非套接字上进行套接字操作
  #define EDESTADDRREQ 89 /* Destination address required */需要目的地址
  #define EMSGSIZE 90 /* Message too long */消息太长
  #define EPROTOTYPE 91 /* Protocol wrong type for socket */错误协议类型
  #define ENOPROTOOPT 92 /* Protocol not available */协议不可用
  #define EPROTONOSUPPORT 93 /* Protocol not supported */不支持协议
  #define ESOCKTNOSUPPORT 94 /* Socket type not supported */不支持套接字类型
  #define EOPNOTSUPP 95 /* Operation not supported on transport endpoint */操作上不支持传输端点
  #define EPFNOSUPPORT 96 /* Protocol family not supported */不支持协议族
  #define EAFNOSUPPORT 97 /* Address family not supported by protocol */协议不支持地址群
  #define EADDRINUSE 98 /* Address already in use */地址已被使用
  #define EADDRNOTAVAIL 99 /* Cannot assign requested address */无法分配请求的地址
  #define ENETDOWN 100 /* Network is down */网络已关闭
  #define ENETUNREACH 101 /* Network is unreachable */网络不可达
  #define ENETRESET 102 /* Network dropped connection because of reset */网络由于复位断开连接
  #define ECONNABORTED 103 /* Software caused connection abort */软件导致连接终止
  #define ECONNRESET 104 /* Connection reset by peer */连接被对方复位
  #define ENOBUFS 105 /* No buffer space available */没有可用的缓存空间
  #define EISCONN 106 /* Transport endpoint is already connected */传输端点已连接
  #define ENOTCONN 107 /* Transport endpoint is not connected */传输端点未连接
  #define ESHUTDOWN 108 /* Cannot send after transport endpoint shutdown */传输端点关闭后不能在发送
  #define ETOOMANYREFS 109 /* Too many references: cannot splice */太多的引用:无法接合
  #define ETIMEDOUT 110 /* Connection timed out */连接超时
  #define ECONNREFUSED 111 /* Connection refused */连接被拒绝
  #define EHOSTDOWN 112 /* Host is down */主机已关闭
  #define EHOSTUNREACH 113 /* No route to host */无法路由到主机
  #define EALREADY 114 /* Operation already in progress */操作已在进程中
  #define EINPROGRESS 115 /* Operation now in progress */进程中正在进行的操作
  #define ESTALE 116 /* Stale NFS file handle */
  #define EUCLEAN 117 /* Structure needs cleaning */
  #define ENOTNAM 118 /* Not a XENIX named type file */
  #define ENAVAIL 119 /* No XENIX semaphores available */
  #define EISNAM 120 /* Is a named type file */
  #define EREMOTEIO 121 /* Remote I/O error */
  #define EDQUOT 122 /* Quota exceeded */
  #define ENOMEDIUM 123 /* No medium found */
  #define EMEDIUMTYPE 124 /* Wrong medium type */


以上补充部分转自:http://blog.youkuaiyun.com/poechant/article/details/7627894#,在此表示感谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值