Finding count of currently open file descriptors.

Andrew McNamara andrewm at object-craft.com.au
Fri Aug 2 04:24:58 CEST 2002


>> 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?

If there is a version of "lsof" that works on your system, you may want
to try it.

>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

I would suggest os.fstat(fd) here - it can return data about the file
descriptor that might help you locate your leak (as well as being
non-destructive).

>     except (OSError),(e):
>         if e.errno == EBADF:
>             print "non existent fd"
>         else:
>             print "something really messed up"
-- 
Andrew McNamara, Senior Developer, Object Craft
http://www.object-craft.com.au/




More information about the Python-list mailing list