您的位置:首页 > 其它

socket select 超时问题 导致CPU高

2017-05-24 10:30 573 查看
以下代码问题在哪里,会不会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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  select