在某些系统上(见下文),您可以在/ 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来自贝尔实验室
想到哪个应该适用于任何*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)