Skip to main content
GameDev.net gamedev.net
🔒 Locked

Thread A closes Thread B's socket?

Started by CWizard Jan 2, 2003 at 4:20 PM 1 replies 600+ views
Original Post
CWizard
CWizard
Let''s say thread B sits on a blocking connect() or accept(), and then thread A comes and close the socket in question. What happens? Will connect()/accept() return with an error, or will hell break loose? Is the behaviour defined, or is this forbidden? I''m particulary interested in those two functions, but also in lesser degree how recv() and send() etc. react when a the socket they''re operating on suddenly is closed. Will closesocket() perhaps wait until they are done, or "queue" the closing. Can someone shed some light on this? Thanks.
johnnie2
johnnie2
Nothing chaotic will happen if a thread closes another thread''s socket during a blocking call.

connect() will return SOCKET_ERROR if the socket passed to it is suddenly closed. Then it''s just a matter of testing whether the socket is an INVALID_SOCKET to determine if the other thread was just doing its job (that is, if your other thread manually sets the socket to INVALID_SOCKET).

If the "server" socket passed to accept() is closed unexpectedly, the returned socket will be an INVALID_SOCKET.

recv() and send() will both return SOCKET_ERROR if the passed socket goes bad. Just for clarification, recv() returns zero on a graceful shutdown (a shutdown() call has been issued for that socket), and some positive value on a successful receive to indicate how many bytes have been copied.

And no, closesocket() will react immediately. You can mimic its behavior by setting the socket to INVALID_SOCKET, which will similarly force any blocking calls to fall through.

I''m assuming you''re trying to find some way to attach a timeout to blocking calls, so you might want to look into setsockopt() or asynchronous sockets. Also, blocking sockets do have an embedded timeout by default, but it may extend to a minute or two in the worst cases. Your solution, however, will work well without incident.

RapscallionGL - arriving soon.
____________"Optimal decisions, once made, do not need to be changed." - Robert Sedgewick, Algorithms in C
CWizard
CWizard
Thanks for your info. What I try to do is to wrap connections into a class, which upon creation spawns a thread which handle the connection. The parent thread call a member function of the class to, among other things, close the connection. This function sets a signal which causes the child thread to abort what it is doing if it is in an established connection (doing send() and recv()). But if it is stuck in either connect() or accept(), I need a way to break out. Doing a closesocket() seem to be enough then.

Thanks again.


Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.