在* NIX系统上,有没有办法找出当前运行过程中有多少个打开的文件句柄?
我正在寻找一个在C中使用的API或公式,从正在运行的进程中.
解决方法
在某些系统上(见下文),您可以在/ proc / [pid] / fd中计算它们.如果没有其中一个,请参见下面的:
wallyk’s answer.
在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; }
在bash中,类似于:
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