Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting count of current used file descriptors from C code

Tags:

c

linux

Is there a C API to get the:

  1. Current used file descriptors system wide
  2. Current used file descriptors of the current process
like image 734
Vivek Goel Avatar asked Nov 02 '11 06:11

Vivek Goel


People also ask

How many file descriptors are there?

Linux systems limit the number of file descriptors that any one process may open to 1024 per process. (This condition is not a problem on Solaris machines, x86, x64, or SPARC). After the directory server has exceeded the file descriptor limit of 1024 per process, any new process and worker threads will be blocked.

How do I find the file descriptors of a process?

You can use /proc file system or the lsof command to find all the file descriptors used by a process.


1 Answers

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.

like image 171
R.. GitHub STOP HELPING ICE Avatar answered Oct 13 '22 00:10

R.. GitHub STOP HELPING ICE