免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1282 | 回复: 0
打印 上一主题 下一主题

select的用法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-12-28 17:37 |只看该作者 |倒序浏览
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
函数的最后一个参数timeout显然是一个超时时间值,其类型是struct timeval *,即一个struct timeval结构的变量的指针,所以我们在程序里要申明一个struct timeval tv;然后把变量tv的地址&tv传递给select函数。struct timeval结构如下:
struct timeval {
             long    tv_sec;         /* seconds */
             long    tv_usec;        /* microseconds */
         };
   第2、3、4三个参数是一样的类型: fd_set *,即我们在程序里要申明几个fd_set类型的变量,比如rdfds, wtfds, exfds,然后把这个变量的地址&rdfds, &wtfds, &exfds 传递给select函数。这三个参数都是一个句柄的集合,第一个rdfds是用来保存这样的句柄的:当句柄的状态变成可读的时系统就会告诉select函数返回,同理第二个wtfds是指有句柄状态变成可写的时系统就会告诉select函数返回,同理第三个参数exfds是特殊情况,即句柄上有特殊情况发生时系统会告诉select函数返回。
#include
#include
#include
#include
#include
      
#define ENABLE_TIMEOUT
      
int main()     {
      int ret;
                 char buf[16];
#ifdef ENABLE_TIMEOUT                 
      fd_set fds;
      struct timeval tv;
  
      
      
      FD_ZERO(&fds);
      FD_SET(STDIN_FILENO,&fds);//把标准输入加入监控
      
      
      tv.tv_sec = 5;
      tv.tv_usec = 0;
      
      //监控标准输入的写集合
        ret = select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
        
        
        if(ret < 0)
                  {  
         perror("select");
         exit(-1);
         
        }else if(ret == 0)
                    {//5 秒钟内用户没有按下键
               printf("timeout
");
                        }
else
#endif

    { //读入用户输入
     scanf("%14s", buf);
        printf("your input %s
",buf);
     }
}
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/108685/showart_2133340.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP