Socket being garbage collected too early

Mike Meyer mwm at mired.org
Thu Dec 16 20:05:00 EST 2004


Scott Robinson <dscottr at bellatlantic.net> writes:

> I have been having trouble with the garbage collector and sockets.
> Unfortunately, google keeps telling me that the problem is the garbage
> collector ignoring dead (closed?) sockets instead of removing live
> ones.  My problem is
>
>
> 	x.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
> 	do_stuff(x.sock)
>
>
> def do_stuff(sock):
> 	sock_list.append(sock)
>
>
> once do_stuff finishes, x.sock disappears, and I can only believe it
> is being garbage collected.  I'd like to hear the standard means for
> avoiding this issue (gc appears to have only the interface to declare
> something garbage, not to declare something not garbage).

The code as shown doesn't work:

 >> import socket
 >> def do_stuff(sock):
 ..   sock_list.append(sock)
 .. 
 >> sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 >> do_stuff(sock)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in do_stuff
NameError: global name 'sock_list' is not defined
 >> 

If you add "sock_list = []" just before the def of do_stuff, the code
will work, and your sockets won't get garbage collected.

     <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list