Should I close the sockets when my application closes?

393 views Asked by At

I have 100+ sockets in my server application, should I call closesocket() on these 100+ sockets when my application is about to close?

Is it possible for closesocket() not to return until the connection is closed for each socket, and hence delay the time it takes for my application to close?

2

There are 2 answers

3
matrumz On

Letting the OS close a socket (or free memory, etc) is a safety feature and should not be solely relied on. It is always a good idea to have a clean exit where your code cleans up after itself.

In C, you would be using close(). See the socket man page for questions on delay: http://linux.die.net/man/7/socket

SO_LINGER

Sets or gets the SO_LINGER option. The argument is a linger structure.

struct linger {
     int l_onoff;    /* linger active */
     int l_linger;   /* how many seconds to linger for */ };

When enabled, a close(2) or shutdown(2) will not return until all queued messages for the socket have been successfully sent or the linger timeout has been reached. Otherwise, the call returns immediately and the closing is done in the background. When the socket is closed as part of exit(2), it always lingers in the background.

0
Stuart On

Yes, it is possible for closesocket not to return immediately and delay the closing of your program. See the SO_LINGER and SO_DONTLINGER and the setsockopt function for more details.

https://msdn.microsoft.com/en-us/library/windows/desktop/ms740476(v=vs.85).aspx