select定时器的简单实现

13 篇文章 4 订阅
   int select(int nfds, fd_set *readfds, fd_set *writefds,
              fd_set *exceptfds, struct timeval *timeout);

   void FD_CLR(int fd, fd_set *set);//从指定的文件描述符集合中删除指定文件描述符fd
   int  FD_ISSET(int fd, fd_set *set);//判断文件描述符fd 是否存在于文件描述符集合set中
   void FD_SET(int fd, fd_set *set);// 将文件描述符fd 放到 文件描述符集合set中
   void FD_ZERO(fd_set *set); //清空一个文件描述符集合



nfds : 文件描述符数量,不过指的是 所包含的最大文件描述符 +1 的值
readfds:可读的 文件描述符集合
writefds:可写的 文件描述符集合
exceptfds:异常的文件描述符集合
timeout 超时设置,阻塞。如果不实现超时设置,那么该函数会死等

 EINTR  A signal was caught; see signal(7). 阻塞等待 可以被信号打断

  EINVAL nfds is negative or exceeds the RLIMIT_NOFILE resource limit (see getrlimit(2)).

   EINVAL the value contained within timeout is invalid.

   ENOMEM unable to allocate memory for internal tables.

   The time structures involved are defined in <sys/time.h> and look like

秒+微秒
           struct timeval {
               long    tv_sec;         /* seconds */
               long    tv_usec;        /* microseconds */
           };

基于select函数的特性,我们可以用它来实现一个安全的休眠

/* select定时器 */
void selectAlrm(int sec)
{
   struct timeval tm;

   tm.tv_sec = sec;
   tm.tv_usec = 0;

   select(0, NULL, NULL, NULL, &tm);
   return ;
}

微秒级别的实现方法一致;

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值