Reputation: 1659
I am using Winsock under VS 2008.
I have a thread dedicated to accepting incoming TCP connection requests via a blocking call to accept(). When the time comes for my app to shut down, I need to somehow unblock this thread so it can perform its shutdown work and exit. Is there a way I may unblock accept()?
I will post another question in case there is no way to unblock accept(). That question is: If I perform a hard kill of the thread that is blocked on accept(), will anything bad happen (corruption of OS data structures, etc.)?
Thanks, Dave
Upvotes: 10
Views: 9033
Reputation: 596287
One way to unblock a blocking accept()
is to close the listening socket from another thread. Otherwise, you can put the listening socket into non-blocking mode and use select()
(which does support a timeout) to detect when accept()
can be called without blocking.
Upvotes: 10
Reputation: 841
Straight forward and specific for Windows, closesocket() returns without error and unblocks a thread calling accept().
Polling on select() is not really what you want! Connecting from an additional thread is not really what you want!
E.g. for linux, close(socket) does not unblock a listening thread, but shutdown(socket, SHUT_RD) will; in addition the socket needs to be closed.
Upvotes: 2
Reputation: 69
A robust way to unblock the accept() call from another thread is to create a connection by using connect(). Of course, the thread needs to know what IP address and port is being listened.
Upvotes: 2
Reputation: 1780
One approach I've used in the past is to supply a timeout value for accept() - and when it timesout, you check a "cancel" flag - if set, you stop - if not, you go back into the loop with the accept() call.
I think killing the thread would work, but you should be careful to ensure it's your thread and, for example, not a .NET threadpool thread.
EDIT: Remy's right, and to think I even did a quick google to verify the struct I recall exists - too quick, it seems. Blush/etc.
If you want to maintain the blocking semantics, it would see closing the socket from another thread (or Aborting your blocking thread) would be the way to go.
Upvotes: 0