【B2B研发商城】 【加入收藏】 【设为首页】 【进入论坛】 【站点地图】

你的位置:中国研发网 >> 技术文章 >> web开发 >> 详细内容 在线投稿

网络开发中的Select的用法详解

热度130票  浏览32次 【共0条评论】【我要评论 时间:2009年12月29日 09:56
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 <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
      
#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);
     }
}
TAG: 开发 网络 详解
顶:5 踩:5
对本文中的事件或人物打分:
当前平均分:0.27 (48次打分)
对本篇资讯内容的质量打分:
当前平均分:-0.67 (39次打分)
【已经有33人表态】
2票
感动
6票
路过
5票
高兴
4票
难过
3票
搞笑
5票
愤怒
4票
无聊
4票
同情
上一篇 下一篇
发表评论

网友评论仅供网友表达个人看法,并不表明本网同意其观点或证实其描述。

查看全部回复【已有0位网友发表了看法】