Getting count of current used file descriptors from C code
For the current process count, you can use
getrlimit to get the file descriptor limit, then iterate over all integers from 0 to that limit and try calling
fcntl with the
F_GETFD command. It will succeed only on the file descriptors which are actually open, letting you count them.
Edit: I now have a better way to do it. After getting the
rlimit, make a large array of
struct pollfd (as large as the limit if possible; otherwise you can break it down into multiple runs/calls) with each fd in the range and the
events member set to 0. Call
poll on the array with 0 timeout, and look for the
POLLNVAL flag in the
revents for each member. This will tell you which among a potentially-huge set of fds are invalid with a single syscall, rather than one syscall per fd.
You can read
/proc/sys/fs/file-nr to find the total number of allocated and free file system handles as well as the maximum allowed.
[[email protected] proc]# cat /proc/sys/fs/file-nr 3853 908 53182 | | | | | | | | max: maximum open file descriptors | free: total free allocated file descriptors allocated: total allocated file descriptors since boot
To calculate the number that are currently in use, just do
allocated - free. You could also calculate a percentage of used descriptors by doing
((allocated - free) / max) * 100
As for per-process, I'm not sure of any programmatic way you can do it.
Here's a tutorial on how to do it with
lsof anyway: http://linuxshellaccount.blogspot.com/2008/06/finding-number-of-open-file-descriptors.html
Since you say you are on Linux, you can open the folder
/proc/self/fd/ which should contain symbolic links to all open file descriptors.