以下代码问题在哪里,会不会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进行文件描述符监测的代码片段,并指出了其中存在的超时问题。该问题源于每次调用select时未重新设置超时值,导致实际超时时间逐渐减少直至几乎为0,从而引起CPU占用率异常增高。文章提供了正确的实现方式,强调了每次调用前都需要重新设定超时值的重要性。
310

被折叠的 条评论
为什么被折叠?



