Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find current number of open filehandle ( NOT lsof )

On *NIX systems, is there a way to find out how many open filehandles are there in the current running process?

I am looking for an API or a formula for use in C, from within the running process in question.

like image 374
ϹοδεMεδιϲ Avatar asked Nov 17 '11 07:11

ϹοδεMεδιϲ


People also ask

How can I find out what process has a file open?

To see the open files for a process, select a process from the list, select the View->Lower Panel View->Handles menu option. All of the handles of type "File" are the open files.

How many file descriptors are open Linux?

Linux systems limit the number of file descriptors that any one process may open to 1024 per process.


1 Answers

On certain systems (see below) you can count them in /proc/[pid]/fd. If not on one of those, see below for: wallyk's answer.

In c, you can list the dir and count the total, or list the dir contents:

 #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 filesystem include, but are not limited to:
Solaris
IRIX
Tru64 UNIX
BSD
Linux (which extends it to non-process-related data)
IBM AIX (which bases its implementation on Linux to improve compatibility)
QNX
Plan 9 from Bell Labs

like image 132
chown Avatar answered Nov 15 '22 00:11

chown