select函数用来填充一组可用的socket句柄,当满足如下条件时:
1.可以读取的sockets。当这些socket被返回时,在这些socket上执行recv/accept等操作不会产生阻塞;
2.可以写入的sockets。当这些socket被返回时,在这些socket上执行send等不会产生阻塞;
3.返回有错误的sockets。
同时和select配对使用的还有:
FD_CLR(s, *set)
Removes the descriptor s from set.
FD_ISSET(s, *set)
Nonzero if s is a member of the set. Otherwise, zero.
FD_SET(s, *set)
Adds descriptor s to set.
FD_ZERO(*set)
Initializes the set to the null set.
示例代码:
1.可以读取的sockets。当这些socket被返回时,在这些socket上执行recv/accept等操作不会产生阻塞;
2.可以写入的sockets。当这些socket被返回时,在这些socket上执行send等不会产生阻塞;
3.返回有错误的sockets。
同时和select配对使用的还有:
FD_CLR(s, *set)
Removes the descriptor s from set.
FD_ISSET(s, *set)
Nonzero if s is a member of the set. Otherwise, zero.
FD_SET(s, *set)
Adds descriptor s to set.
FD_ZERO(*set)
Initializes the set to the null set.
示例代码:
SOCKET s;
fd_set fdread;
int ret;
// Create a socket, and accept a connection
// Manage I/O on the socket
while(TRUE)
{
// Always clear the read set before calling
// select()
FD_ZERO(&fdread);
// Add socket s to the read set
FD_SET(s, &fdread);
if ((ret = select(0, &fdread, NULL, NULL, NULL))
== SOCKET_ERROR)
{
// Error condition
}
if (ret > 0)
{
// For this simple case, select() should return
// the value 1. An application dealing with
// more than one socket could get a value
// greater than 1. At this point, your
// application should check to see whether the
// socket is part of a set.
if (FD_ISSET(s, &fdread))
{
// A read event has occurred on socket s
}
}
}
fd_set fdread;
int ret;
// Create a socket, and accept a connection
// Manage I/O on the socket
while(TRUE)
{
// Always clear the read set before calling
// select()
FD_ZERO(&fdread);
// Add socket s to the read set
FD_SET(s, &fdread);
if ((ret = select(0, &fdread, NULL, NULL, NULL))
== SOCKET_ERROR)
{
// Error condition
}
if (ret > 0)
{
// For this simple case, select() should return
// the value 1. An application dealing with
// more than one socket could get a value
// greater than 1. At this point, your
// application should check to see whether the
// socket is part of a set.
if (FD_ISSET(s, &fdread))
{
// A read event has occurred on socket s
}
}
}