socket select 超时问题 导致CPU高

以下代码问题在哪里,会不会select每次1秒超时呢?
void IPCServer::DoWork()
{
 fd_set read_set;
 struct timeval tv_select;
 tv_select.tv_sec = 1;
 tv_select.tv_usec = 0;

 int max_fd = m_nListenSocket;
 int r = 0;
 
 struct sockaddr_in addr_client;
 socklen_t addr_len = sizeof(addr_client);;

 char buffer[IPC_MAX_BUF_LEN] = {0};
 
 while(true)
 {
  FD_ZERO(&read_set);
  FD_SET(m_nListenSocket, &read_set);
  r = select(max_fd + 1, &read_set, NULL, NULL, &tv_select);
 }
}

man select

DESCRIPTION
       select()  and  pselect()  allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of
       I/O operation (e.g., input possible).  A file descriptor is considered ready if it is possible to perform the corresponding I/O operation (e.g., read(2))  without
       blocking.

       The operation of select() and pselect() is identical, with three differences:

       (i)    select() uses a timeout that is a struct timeval (with seconds and microseconds), while pselect() uses a struct timespec (with seconds and nanoseconds).

       (ii)   select() may update the timeout argument to indicate how much time was left.  pselect() does not change this argument.

每调用一次select timeout是上一次的剩余时间,即第二次都是为0,会导致什么问题呢,频繁调用导致CPU高。

       (iii)  select() has no sigmask argument, and behaves as pselect() called with NULL sigmask.


正确应该每次都重新赋值(或采用pselect)

  struct timeval tv_select;
  tv_select.tv_sec = 1;
  tv_select.tv_usec = 0;
  r = select(max_fd + 1, &read_set, NULL, NULL, &tv_select);






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值