关于如何在 TCP 中使用 select() 的困惑

Confusion on how to use select() in TCP

int select(int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds,
           struct timeval *timeout);

readfds & writefds - 它们可以同时使用吗?例如:如果我有一个读取操作和一个发送操作一个接一个

另外,谁能提供一个好的link或示例程序?

select(...)是否仅用于服务器程序?或者仅在 TCP 中?

来自manual

Three independent sets of file descriptors are watched. Those listed in readfds will be watched to see if characters become available for reading (more precisely, to see if a read will not block; in particular, a file descriptor is also ready on end-of-file), those in writefds will be watched to see if a write will not block, and those in exceptfds will be watched for exceptions. On exit, the sets are modified in place to indicate which file descriptors actually changed status. Each of the three file descriptor sets may be specified as NULL if no file descriptors are to be watched for the corresponding class of events.

小例子提供 readfds:

fd_set set;

FD_SET(0,&set); //stdin
FD_SET(socket,&set); //socket may be your tcp-fd where you wanna read from

while(1) {

select(socket,&set,NULL,NULL,NULL) 

FD_ZERO(&set);
FD_SET(0,&set);
FD_SET(socket,&set);

if(FD_ISSET(0,&set)) 
{
 //write the input on the stream
}

if(FD_ISSET(socket,&set)) 
{
 //read any content from the stream

}
}

只需声明一组 writefds,并使用 FD_ISSET 检查它们的状态,它应该 simuntanouesly.

Select() 可以在任何你想处理多个描述符的地方使用。