[Python-Dev] sock.close() not closing? (original) (raw)

Sjoerd Mullender sjoerd at acm.org
Wed May 7 16:37:20 CEST 2008


On 2008-05-07 13:37, Amaury Forgeot d'Arc wrote:

Hello,

2008/5/7 Sjoerd Mullender <sjoerd at acm.org>: Why does sock.close() not actually close sock?

If I run the code import socket sock = socket.socket() ... sock.close() I would expect that a system call is done to actually close the socket and free the file descriptor. But that does not happen. Look at the code in socket.py. It merely replaces the socket instance with a dummy instance so that all subsequent calls on the sock object fail, but it does nothing else! It does close the socket: In socket.py, when self.sock is replaced, its del method will be called. This del is implemented in C, in socketmodule.c: static void sockdealloc(PySocketSockObject *s) { if (s->sockfd != -1) (void) SOCKETCLOSE(s->sockfd); PyTYPE(s)->tpfree((PyObject *)s); } Of course, if you call sock.dup() or sock.makefile(), there is another reference to the underlying sock, and you must close() all these objects.

I have to question the design of this. When I close() an object I expect it to be closed there and then and not at some indeterminate later time (well, it is determinate when you're fully aware of all references, but often you aren't--trust me, I understand reference counting).

Then there also seems to be a bug in imaplib.IMAP4_SSL since in its shutdown method it closes the socket but leaves the sslobj untouched. I assume that that object keeps a reference to the socket.

But as I said, I expect the close() to actually close.

-- Sjoerd Mullender



More information about the Python-Dev mailing list