Find the current number of open file descriptors (NOT lsof)

On * NIX systems, is there a way to find out how many open file descriptors exist in the currently running process?

I am looking for an API or formula to use in C as part of the current process.

+6
source share
4 answers

On some systems (see below) they can be converted to / proc / [pid] / fd. If not on one of them, see below: wallyk answer .

In c, you can list the directory and calculate the total or list the contents of the directory:

#include <stdio.h> #include <sys/types.h> #include <dirent.h> int main (void) { DIR *dp; struct dirent *ep; dp = opendir ("/proc/MYPID/fd/"); if (dp != NULL) { while (ep = readdir (dp)) puts (ep->d_name); (void) closedir (dp); } else perror ("Couldn't open the directory"); return 0; } 

In bash, something like:

 ls -l /proc/[pid]/fd/ | wc -l 

Operating systems that support the proc file system include, but are not limited to:
Solaris
IRIX
Tru64 UNIX
BSD
Linux (which extends it to non-process data)

IBM AIX (which bases its implementation on Linux to increase compatibility)
QNX
Plan 9 from Bell Labs

+6
source

An idea that comes to mind that should work on any * nix system:

 int j, n = 0; // count open file descriptors for (j = 0; j < FDMAX; ++j) // FDMAX should be retrieved from process limits, // but a constant value of >=4K should be // adequate for most systems { int fd = dup (j); if (fd < 0) continue; ++n; close (fd); } printf ("%d file descriptors open\n", n); 
+6
source

OpenSSH implements a closefrom function that does something very similar to what you need, mixing the two approaches already proposed by wallyk and chown, and OpenSSH is very portable, at least between Unix / Linux / BSD / Cygwin systems.

+1
source

There is no portable way to get the number of open descriptors (regardless of type) if you yourself do not track them.

0
source

Source: https://habr.com/ru/post/901695/


All Articles