Finding count of currently open file descriptors.

Holden Caulfield phoebe_1 at att.net
Thu Aug 1 11:15:00 EDT 2002


Tim McNerney <tmcnerney at truis.com> wrote in message news:<3D469D2F.6010003 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?
> 
> Thanks.
> 
> --Tim

This is part of the snippet of code, that I use, you can change it to
suit
your needs:

from errno import EBADF
try:
  import os
  max_fds = os.sysconf('SC_OPEN_MAX')
except (ValueError),(e):
  print "oh well, go the C route"
else:
  for fd in xrange(3,max_fds):
     try:
         os.close(fd)    # or do anything else to check if fd is valid
     except (OSError),(e):
         if e.errno == EBADF:
             print "non existent fd"
         else:
             print "something really messed up"

Obviously, I am ignoring the stdin,stdout and stderr in the xrange.
Also, this might only work in UNIX.
Dave's C solution might be faster as he said.



More information about the Python-list mailing list