473,788 Members | 2,800 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Socket being garbage collected too early

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.s ocket(socket.AF _INET,socket.SO CK_STREAM)
do_stuff(x.sock )
def do_stuff(sock):
sock_list.appen d(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).

Scott Robinson

Jul 18 '05 #1
4 2952
Scott Robinson wrote:
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.s ocket(socket.AF _INET,socket.SO CK_STREAM)
do_stuff(x.sock )
def do_stuff(sock):
sock_list.appen d(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).

Scott Robinson

Unfortunately, assuming it's being garbage collected might turn out to
be incorrect. What evidence do you have that the socket "disappears "? Do
you get a segmentation ault, or what?

If the socket simply fails to work that would be a different case
altogether, but it seems to me that we need a bit more evodence that the
anecdotal stuff you've provided so far.

Quite apart from anything else, by the way, the code you posted appears
to use a global sock_list. A reference b y that list would in any case
stop the socket from being garbage collected (quite apart from the fact
that the socket module itself will do so as long as the socket is open).

So, could we see an error message, or some other evidence of what is
going on. For example, after the call to do_stuff(), what do you see if you

print sock_list

for example. I think your initial hypothesis is insufficient.

regards
Steve
--
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/
Holden Web LLC +1 703 861 4237 +1 800 494 3119
Jul 18 '05 #2
Scott Robinson <ds*****@bellat lantic.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.s ocket(socket.AF _INET,socket.SO CK_STREAM)
do_stuff(x.sock )
def do_stuff(sock):
sock_list.appen d(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.appen d(sock)
.. sock = socket.socket(s ocket.AF_INET,s ocket.SOCK_STRE AM)
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 <mw*@mired.or g> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
Jul 18 '05 #3
Scott Robinson <ds*****@bellat lantic.net> writes:
I have been having trouble with the garbage collector and sockets.
Are you actually getting errors or is this just theoretical?
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.s ocket(socket.AF _INET,socket.SO CK_STREAM)
do_stuff(x.sock )
def do_stuff(sock):
sock_list.appen d(sock)

once do_stuff finishes, x.sock disappears, and I can only believe it
is being garbage collected.


Can you clarify this? What do you mean by "x.sock" disappears? Are
you getting a NameError later when trying to use "x.sock"?

x.sock is just a name binding, so it is not really involved in garbage
collection (GC applies to the objects to which names are bound).

In this case, you need to include much more in the way of code (a
fully running, but smallest possible, snippet of code would be best),
since the above can be interpreted many ways. At the least, it's very
important to include information about the namespace within which
those two code snippets run if anyone is likely to be able to give you
a good answer. Also, being very precise about the error condition you
are experiencing (including actual error messages, tracebacks, etc...)
is crucial.

Is 'x' referencing a local or global object, and does that socket code
occur within a method, a function, or what? Also, in do_stuff, where
is sock_list defined? Is it local, global?

If, as written, sock_list is a local name to do_stuff, then that
binding is going to disappear when do_stuff completes, thus, the list
to which it is bound will be destroyed, including all references to
objects that the list may contain. So at that point, when you return
from do_stuff, the only reference to the socket object will be in
x.sock. But if 'x' is also local to the function/method where the
call to do_stuff is, the name binding will be removed when the
function/method returns, at which point there will be no references to
the socket object, and yes, it will be destroyed.

But if sock_list is global, and continues to exist when do_stuff
completes, then the reference it contains to the socket will keep the
socket object alive even if you remove the x.sock binding.

-- David

Jul 18 '05 #4
On 16 Dec 2004 20:38:29 -0500, David Bolen <db**@fitlinxx. com> wrote:
Scott Robinson <ds*****@bellat lantic.net> writes:
I have been having trouble with the garbage collector and sockets.


Are you actually getting errors or is this just theoretical?
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.s ocket(socket.AF _INET,socket.SO CK_STREAM)
do_stuff(x.sock )
def do_stuff(sock):
sock_list.appen d(sock)

once do_stuff finishes, x.sock disappears, and I can only believe it
is being garbage collected.


Can you clarify this? What do you mean by "x.sock" disappears? Are
you getting a NameError later when trying to use "x.sock"?

x.sock is just a name binding, so it is not really involved in garbage
collection (GC applies to the objects to which names are bound).

In this case, you need to include much more in the way of code (a
fully running, but smallest possible, snippet of code would be best),
since the above can be interpreted many ways. At the least, it's very
important to include information about the namespace within which
those two code snippets run if anyone is likely to be able to give you
a good answer. Also, being very precise about the error condition you
are experiencing (including actual error messages, tracebacks, etc...)
is crucial.

Is 'x' referencing a local or global object, and does that socket code
occur within a method, a function, or what? Also, in do_stuff, where
is sock_list defined? Is it local, global?

If, as written, sock_list is a local name to do_stuff, then that
binding is going to disappear when do_stuff completes, thus, the list
to which it is bound will be destroyed, including all references to
objects that the list may contain. So at that point, when you return
from do_stuff, the only reference to the socket object will be in
x.sock. But if 'x' is also local to the function/method where the
call to do_stuff is, the name binding will be removed when the
function/method returns, at which point there will be no references to
the socket object, and yes, it will be destroyed.

But if sock_list is global, and continues to exist when do_stuff
completes, then the reference it contains to the socket will keep the
socket object alive even if you remove the x.sock binding.

-- David

(so much for Python being executable psuedocode).

It looks like I was completely wrong. The problem I ran into was not
checking into baseHTTPserver and looking for self.close_conn ection=1.

I am pretty sure this happened to me before, and I rewrote the code to
avoid sockets being closed after being referenced to a live object,
but I can't reproduce it.

Anyway, here is my debugged test rig. It works. Ignore it.
Scott
[test program follows]
import socket, thread, time

class sock_holder:
pass

HOST = '127.0.0.1'
PORT = 2004

def echo_server(por t):
print "started at",port
s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
s.bind((HOST, port))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
data = conn.recv(1024)
if not data: break
conn.send(data)
conn.close()

def wait_and_speak( a):
time.sleep(5)
try:
a.sock.send("th is is message 2")
except:
print "error on message 2"
try:
data = a.sock.recv(102 4)
print data
except:
print "error recieving message 2"
a.sock.close()

def other_thread(a) :
s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
thread.start_ne w(echo_server,( PORT,))
time.sleep(1)
s.connect((HOST ,PORT ))
s.send('Hello, port 1')
data = s.recv(1024)
print data
a.sock=s

thread.start_ne w(wait_and_spea k,(a,))

a=sock_holder()
thread.start_ne w(other_thread, (a,))
time.sleep(10)
Jul 18 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
9114
by: Daniel | last post by:
TcpClient close() method socket leak when i use TcpClient to open a connection, send data and close the TcpClient with myTcpClientInstance.Close(); it takes 60 seconds for the actual socket on the client machine to close per my network app the computer fills up w/ thousands of these :0 TCP foobox:8888 localhost:2188 TIME_WAIT :0 TCP foobox:8888 localhost:2189 TIME_WAIT :0 TCP foobox:8888 localhost:2190 TIME_WAIT
8
21913
by: Grant Richard | last post by:
Using the TcpListener and TcpClient I created a program that just sends and receives a short string - over and over again. The program is fine until it gets to around 1500 to 1800 messages. At that time, I get a SocketException with the message "Only one usage of each socket address (protocol/network address/port) is normally permitted". This happen if you use localhost or between two distinct computers. And, for a period of time after the...
2
2118
by: C P | last post by:
I'm coming from Delphi where I have to explicitly create and destroy instances of objects. I've been working through a C#/ASP.NET book, and many of the examples repeat the same SqlConnection, SqlDataAdapter etc. objects, so I thought I'd create a class with a bunch of factory methods to create my classes for me. But, I'm unclear about how garbage collection works, and if it is safe to do this. It seems to compile, but am I asking for...
5
2830
by: Razzie | last post by:
Hi all, A question from someone on a website got me thinking about this, and I wondered if anyone could explain this. A System.Threading.Timer object is garbage collected if it has no references to it. But what about threads? If I start a new thread that only does 1+1, is it garbage collected after that? If so, do all threads get garbage collected eventually that are 'done'? And if not, why not? Are there references to the thread that...
11
6867
by: Tor Erik | last post by:
Hi, The reason is that my application does about 16 connects and data transfers per second, to the same 16 remote hosts. After approx 200 secs there are 4000 sockets waiting to be garbage collected by the OS. At this point is seems that connect loops and starts using the same local addresses it used 4000 connections ago, resulting in an "Address already in use" exception. A possible solution to this would be to keep the connection to...
6
1778
by: massimo s. | last post by:
Hi, Python 2.4, Kubuntu 6.06. I'm no professional programmer (I am a ph.d. student in biophysics) but I have a fair knowledge of Python. I have a for loop that looks like the following : for item in long_list: foo(item)
10
5187
by: ThunderMusic | last post by:
Hi, I'm currently working with sockets. I accept connections using m_mySocket.Listen(BackLogCount); But when I want to stop listening, I shutdown all my clients and call m_mySocket.Close(), but it always raise a OnConnect event (actually, it calls the callback function as if there was a new connection attempt) and I receive a ObjectDisposedException as soon as I do m_mySocket.EndAccept. Does anyone have any idea of what I could do about...
56
3716
by: Johnny E. Jensen | last post by:
Hellow I'am not sure what to think about the Garbage Collector. I have a Class OutlookObject, It have two private variables. Private Microsoft.Office.Interop.Outlook.Application _Application = null; Private Microsoft.Office.Interop.Outlook.NameSpace _Namespace = null; The Constructor: public OutlookObject()
13
9000
by: Alan Wright | last post by:
Hi Folks, I am newbie to Python, but have successfully created a simple client and server setup, I have one issue though. I am trying to test a box by sending many TCP conns (WHILE loop) but not closing them with a FIN/RST. However, no matter what i do, i cannot get the loop to stop sending FIN from the client. Any clues?
0
10364
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.