当标准输入上有某些内容时,我在选择返回时遇到问题,即使我不希望它这样做。例如,这里的代码旨在等待套接字上的数据一段时间,但是如果标准输入上有数据,则选择返回:
int mylib_UDP_Client_Recv(int sock, void *data, int max_length, int timeout)
//timeout is taken to be milliseconds
{
struct sockaddr_in sdata;
struct timeval timeouts;
timeouts.tv_sec = timeout / 1000;
timeout -= timeouts.tv_sec * 1000;
timeouts.tv_usec = timeout * 1000;
int n;
int maxfd = sock;
fd_set static_rdset, static_wrset, rdset, wrset;
unsigned int datalen = sizeof(struct sockaddr_in);
FD_SET(sock,&static_rdset);
FD_SET(sock,&static_wrset);
rdset = static_rdset;
wrset = static_wrset;
if (select(maxfd+1,&rdset,NULL,&wrset,&timeouts) == 0) //wrset used as exception set
{
return -1; //timed out
}
if (FD_ISSET(sock,&rdset))
{
n = recvfrom(sock,data,max_length,0,(struct sockaddr *)&sdata,&datalen);
if (n < 0) return 0;
return n;
}
else
{
return 0; //error
}
}