Finding count of currently open file descriptors.

Donn Cave donn at u.washington.edu
Tue Jul 30 13:08:09 EDT 2002


Quoth Tim McNerney <tmcnerney at truis.com>:
| How do I go about finding out the number of file descriptors currently 
| open in a program? I'm trying to track down a file descriptor leak which 
| may or may not be in library calls. Will I run into problems getting an 
| accurate count due to the possible delay between doing a close and GC?

No, you won't.  The classic technique for this is just to inventory
all possible file descriptors and see which ones are valid - might
sound like a lot of overhead, but it goes pretty fast.  In C, that is.
In Python, you might be able to work around the absence of getdtablesize(),
but this is the rare case where exceptions are not your friend, they'll
add significant overhead.  The number of calls (process file limit)
will be on the order of 64 to 256, depending on platform.

If you can jack in a module, try this - just call fd.count() around
the suspect code.

	Donn Cave, donn at u.washington.edu
----------------------------------------
/*
** NetBSD build:
** cc -c fdmodule.c -I/usr/local/include/python2.1
** ld -shared -o fdmodule.so fdmodule.o -lc
*/
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <Python.h>

static PyObject *
count(PyObject *module, PyObject *args)
{
    int maxfd, fd, vfd;
    maxfd = getdtablesize();
    for (fd = 0, vfd = 0; fd < maxfd; ++fd) {
        if (isatty(fd))
            ++vfd;  /* valid tty */
	else if (errno == ENOTTY)
            ++vfd;  /* not valid tty, but not EBADF */
    }
    return PyInt_FromLong(vfd);
}

static struct PyMethodDef fd_global_methods[] = {
    {"count", count, 1},
    {0, 0}		/* sentinel */
};

initfd()
{
    PyObject *module;
    PyObject *dict;

    module = Py_InitModule("fd", fd_global_methods);
    dict = PyModule_GetDict(module);
    return 1;
}



More information about the Python-list mailing list