查找当前打开的文件句柄数(不是lsof)

Ϲοδ*_*διϲ 6 c c++ unix linux setrlimit

在*NIX系统上,有没有办法找出当前运行过程中有多少个打开的文件句柄?

我正在寻找一个在C中使用的API或公式,从正在运行的进程中.

cho*_*own 6

在某些系统上(见下文),您可以在/ proc/[pid]/fd中计算它们.如果不是其中之一,请参见下文:wallyk的回答.

在c中,您可以列出目录并计算总数,或列出目录内容:

 #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;
 }
Run Code Online (Sandbox Code Playgroud)

在bash中,类似于:

ls -l /proc/[pid]/fd/ | wc -l
Run Code Online (Sandbox Code Playgroud)

支持proc文件系统的操作系统包括但不限于:
Solaris
IRIX
Tru64 UNIX
BSD
Linux(将其扩展到与非流程相关的数据)
IBM AIX(它的实现基于Linux以提高兼容性)
QNX
Plan 9来自贝尔实验室

  • 这对于例如FreeBSD系统来说是不可移植的,因为它们没有/ proc/filesystem.另外:这不符合OP的问题. (2认同)
  • @CodeMedic:wallyk解决方案在任何时候只需要一个额外的文件处理程序,因为它在循环中打开并关闭它. (2认同)

wal*_*lyk 6

想到哪个应该适用于任何*nix系统的想法是:

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);
Run Code Online (Sandbox Code Playgroud)

  • @arne:OP不要求差异化.仅打开文件句柄的总数. (4认同)