socket select 超时问题 导致CPU高

本文分析了一个使用select进行文件描述符监测的代码片段,并指出了其中存在的超时问题。该问题源于每次调用select时未重新设置超时值,导致实际超时时间逐渐减少直至几乎为0,从而引起CPU占用率异常增高。文章提供了正确的实现方式,强调了每次调用前都需要重新设定超时值的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以下代码问题在哪里,会不会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);






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值