How to cleanup after Socket.bind on Linux?

Regan Heath regan at netmail.co.nz
Tue Aug 27 02:02:23 PDT 2013


On Tue, 27 Aug 2013 04:30:10 +0100, Ali Çehreli <acehreli at yahoo.com> wrote:
> The following simple socket example is trying to cleanup after itself,  
> except the bind() call. As I repeat in the QUESTION comment below, I  
> have read the man page of bind and I know that I need to unlink a path.  
> How can I get that path?

That example is for AF_UNIX domain sockets.  TcpSocket is an AF_INET  
domain socket.  In AF_INET there is no 'path' and there is nothing you  
need to do to cleanup after bind - other than close the socket.  I do not  
believe a shutdown is required for a listening socket - tho don't quote me  
on that.

> The problem is, currently the program apparently leakes some resources.  
> It cannot be started a second time for 8080 still being in use, unless  
> you wait for several seconds, presumably until the OS does the cleanup.

Correct.  And this time varies by platform, as dnewbie mentions on Windows  
you can re-use immediately.

You could set the REUSE option on the socket prior to 'bind', this would  
allow you to bind again while the previous socket was in cleanup.

The other thing which might be affecting things is..

Take a look at:
http://linux.die.net/man/7/socket

Specifically "SO_LINGER".  This socket option controls whether and how  
long a socket will linger after it is closed.  I am not sure what the  
linux defaults are for that, but it may be set to linger intentionally.   
You could use getsockopt to obtain the LINGER default values and see.

Also.. the sentence "When the socket is closed as part of exit(2), it  
always lingers in the background." made me think, when does scope(exit)  
fire?  Does it occur as part of exit in your example?  Does manually  
calling shutdown/close on the listening socket resolve the issue.

Regan

-- 
Using Opera's revolutionary email client: http://www.opera.com/mail/


More information about the Digitalmars-d-learn mailing list