我有一个WinSock mySocket
,它像这样循环接收:
while(keepGoing){
FD_SET fsd;
FD_ZERO(&fds);
FD_SET(mySocket, &fds);
int result = select(1+mySocket, &fds, (fd_set *)0, (fd_set *)0, &timeout);
if(result>0 && FD_ISSET(mySocket, &fds){
result = recvfrom(mySocket, buff, NUM_BYTES, (struct sockaddr *)&add, &length);
// do stuff
}
}
如果我想停止接收,我可以将keepGoing
设置为false,但套接字可能仍在等待timeout
才会看到keepGoing
已更改。
假设我们不想更改超时值,是否有可靠的方法告诉套接字停止接收而不等待超时发生?
答案 0 :(得分:1)
当keepGoing
为errno
时,您可以发出良性信号并检查EINTR
标记。或者,您可以创建pipe
并将阅读结尾添加到select
集。设置keepGoing
标志后关闭写入结束。
int quitfds[2];
pipe(quitfds);
//...
FD_SET(quitfds[0], &fds);
//...
if (FD_ISSET(quitfds[0], &fds)) {
close(quitfds[0]);
continue;
}
编辑:Adam指出我错过了问题中的Winsock
引用。您可以使用socketpair
代替pipe
。它似乎没有在Windows上实现,但我发现a workaround here。 Ben指出WSAEventSelect
允许混合不同的事件对象。感谢两者。