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.
/*
* ofiles.c - Displays the number of open files for its own process
* Copyright (C) 2005 Michael Cutler <m@cotdp.com>
*
*/
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
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;
}
Example:
[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 ~]$
About this entry
You’re currently reading “Determine the number of open files in your program (C/C++),” an entry on Weblog of Michael Cutler
- Published:
- 22nd August 2005 / 12:08pm
- Category:
- Uncategorised
Related Entries
- WP Plugin » SpamKit Plugin 0.3 - Time-Based-Tokens to Fight Spam
15th February 2006 - Java Snippet - Using SecureRandom
17th May 2005 - Blogs are fundamentally flawed for the typical Grandma-User
3rd January 2006 - Wordpress 2.0.2 ‘Security Release’
10th March 2006 - Unicode? Character Sets? UTF-what?
9th July 2005
No comments
Jump to comment form | comments rss [?] | trackback uri [?]