bolov
bolov

Reputation: 75825

RAII sockets: when to release (close)

I want to write a simple, small C++ RAII wrapper over a C socket.

The question is in what state is a socket considered initialized (from the perspective of RAII) and so eligible for release.

For instance, for a TCP client socket: if the socket call succeed, but the connect call failed, should close be called?

This is just an example, I am interested in a general answer, something like:

The man pages for socket & friends and close are not very clear (or at least to me).

Upvotes: 9

Views: 1129

Answers (1)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17424

The two parts to pair up for sockets are socket() with close() and connect() with shutdown(). As you see, it doesn't get as easy as with malloc() and free(). This is further complicated by the fact that not every socket is used to connect(), some also use bind() and accept() instead. However, if you call close() without shutdown(), it's just a forceful shutdown that is experienced as an error by the remote side, but you correctly release resources that were allocated.

I'd consider wrapping it twice, once to invoke close() and another time to invoke shutdown(). I wouldn't worry too much about the second part though, as failure to shutdown() is still mostly harmless.

Upvotes: 3

Related Questions