本文介绍了查找当前打开的文件句柄数(不是lsof)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

在某些系统上(请参见下文),您可以在/proc/[pid]/fd中对其进行计数.如果不是其中之一,请参见以下内容: wallyk的答案.

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.

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

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;
 }

在bash中,类似:

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

这篇关于查找当前打开的文件句柄数(不是lsof)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 08:04
查看更多