Determine the number of open files in your program (C/C++)

The code below will display the number of files open by the running process. It does this by getting the maximum file descriptor number and then iterating through each possible fd trying to do an ‘fstat’ on it. If errno returns anything other than EBADF ‘file descriptor is bad’ it increments a count.
It is fairly portable, tested and working on Linux & Solaris.
[cpp]
/*
* ofiles.c – Displays the number of open files for its own process
* Copyright (C) 2005 Michael Cutler
*
*/
#include
#include
#include
#include
#include
#include
#include
extern int errno;
int main ( int argc, char** argv, char** env ) {
int i = 0;
int fd_counter = 0;
int max_fd_number = 0;
struct stat stats;
struct rlimit rlimits;
max_fd_number = getdtablesize();
getrlimit(RLIMIT_NOFILE, &rlimits);
printf( “max_fd_number: %d\n”, max_fd_number );
printf( ” rlim_cur: %d\n”, rlimits.rlim_cur );
printf( ” rlim_max: %d\n”, rlimits.rlim_max );
for ( i = 0; i <= max_fd_number; i++ ) { fstat(i, &stats); if ( errno != EBADF ) { fd_counter++; } } printf( " open files: %d\n", fd_counter ); return 0; } [/cpp] Example: [code] [mcutler@rasco ~]$ gcc -o ofiles ofiles.c [mcutler@rasco ~]$ ./ofiles max_fd_number: 1024 rlim_cur: 1024 rlim_max: 1024 open files: 3 [mcutler@rasco ~]$ [/code]


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *