Chinaunix首页 | 论坛 | 博客
  • 博客访问: 211324
  • 博文数量: 112
  • 博客积分: 275
  • 博客等级: 二等列兵
  • 技术积分: 565
  • 用 户 组: 普通用户
  • 注册时间: 2011-12-20 10:52
文章分类

全部博文(112)

文章存档

2014年(3)

2013年(2)

2012年(64)

2011年(43)

分类:

2012-03-01 17:17:43

使用select和poll对进程的所有描述符进行调用
#include
int select(int maxfd, fd_set * readset, fd_set *writeset, fd_set * exceptset, struct timeval *timeout)
进程运行select会将自己柱塞,直到满足条件(可能是某个描述符可读,某个描述符可写,有异常或者是时间到了)进程才被唤醒。
参数介绍: maxfd 为进程现有的所有描述字的最大数加1
         readset为一个可读的描述字集合的指针
         writeset为一个可写的描述字集合指针
         timeout为告送内核等待某个描述字多少时间,其值可以有3种情况:
          1,参数为null,表示无限等待
          2.定义timeut,等待timeout时间
          3.定义timeout结构为0,表示不等待
函数返回值:-1表示失败,0表示时间到了,正整数表示就绪描述符。

#include

 struct timeval {
 time_t  tv_sec;  /* seconds */  秒
 suseconds_t tv_usec; /* microseconds */ 毫秒
};

 

对readset,writeset和exceptset分别有下列宏进行处理:

void FD_ZERO(fd_set * fdset);  初始化描述符集

void FD_CLE(int fields, fd_set *fd_set ) 从描述符集中将fields清出去

int  FD_ISSET(int fields, fd_set *fd_set ) 判断fields是否在描述符集中

void FD_SET(int fields, fd_set *fd_set ) 将fields加进描述符集中。

 

实例:

 

#include

#include

#include

#include

#define SIZE 100

int main()

{ timeval  tm;

  char buffer[SIZE];

  char buf[]="data has come";

 fd_set  rset;

 FD_ZERO(&rset);

 FD_SET(0,&rset);

for(;;)

{ tm.tv_sec=5;

   tm.tv_usec=0;

  FD_ZERO(&rset);

  FD_SET(0,&rset);

 int result=select(1,&rset,NULL,NULL,&tm); // 柱塞自己,知道标准终端可读或者5秒的

                                                                          时间到了

if(result==-1)

 printf("error!\n");

else if(FD_ISSET(0,&rset)

{  wtite(0,buf,sizeof(buf));

    int num=read(0,buffer,SIZE);

   write(0,buffer,num);

  }

  else

printf("data has not come within the default time!\n");

}

return 0;

}

 

 

 

 

 

阅读(611) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~