UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » Threads
  • » Proper way to close a blocking UDP socket

#1 2011-06-10 11:17 AM

Scott Wilson
Guest

Proper way to close a blocking UDP socket

I have a C++ object that creates a thread to read from a blocking UDP socket:

mRunning.store(true);
while (mRunning.load(boost::memory_order_consume)) {
	...
	int size = recvfrom(mSocket, buf, kTextBufSize , 0,
						(struct sockaddr *) &packet->mReplyAddr.mSockAddr, (socklen_t*)&packet->mReplyAddr.mSockAddrLen);
	
	if (size > 0) {
		//do stuff
	}
}
return 0;

(mRunning is a boost::atomic<bool>)

The object's destructor is called from another thread and does this:

mRunning.store(false);	
#ifdef WIN32
	if (mSocket != -1) closesocket(mSocket);
#else
	if (mSocket != -1) close(mSocket);
#endif
pthread_join(mThread, NULL);

This seems to work, but one of my colleagues suggested that there might be a problem if recv is interrupted in the middle of reading something. Is this thread safe? What's the correct way of closing a blocking UDP socket. (Needs to be cross-platform OSX/Linux/Windows)

#2 2011-06-11 07:35 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,230

Re: Proper way to close a blocking UDP socket

System calls are thread safe, so the recv() itself should be fine.

That said, if the socket gets closed and another one gets opened at the same time,
the new socket may have the same number as the just closed one and you may
receive from a different peer than expected.

So it may be better to kill/close the receiving thread before closing the socket.

The same is true for OSX, no idea about Windows, but it should be okay too.
It would be really stupid if it isn't thread-safe, and I don't expect Windows
to be that bad.

Offline

  • Index
  • » Threads
  • » Proper way to close a blocking UDP socket

Board footer

Powered by FluxBB