I have a WinSock mySocket that receives in a loop like so:
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
}
}
If I want to stop receiving I can set keepGoing to false, but the socket may still be waiting for timeout before it sees that keepGoing has changed.
Assuming that we do not want to change the value of the timeout, is there a reliable way to tell the socket to stop receiving without waiting for the timeout to occur?
You can raise a benign signal and check the
keepGoingflag when theerrnoisEINTR. Or, you can create apipeand add the read end to yourselectset. Close the write end after setting thekeepGoingflag.Edit: Adam points out that I missed the
Winsockreference in the question. You can use asocketpairinstead of apipe. It doesn’t seem to be implemented on Windows, but I found a workaround here. Ben points out thatWSAEventSelectallows mixing of different event objects. Thanks to both.