从C代码获取当前使用的文件描述符的计数 [英] Getting count of current used file descriptors from C code

查看:191
本文介绍了从C代码获取当前使用的文件描述符的计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有C API来获取:

Is there a C API to get the:

  1. 当前系统范围内使用的文件描述符
  2. 当前进程的当前使用的文件描述符

推荐答案

对于当前进程数,可以使用getrlimit获取文件描述符限制,然后遍历从0到该限制的所有整数,然后尝试调用fcntlF_GETFD命令.它只会在实际打开的文件描述符上成功执行,以便您对其进行计数.

For the current process count, you can use getrlimit to get the file descriptor limit, then iterate over all integers from 0 to that limit and try calling fcntl with the F_GETFD command. It will succeed only on the file descriptors which are actually open, letting you count them.

编辑:我现在有一种更好的方法.获得rlimit后,制作一个大型的struct pollfd数组(如果可能的话,请尽可能限制;否则,您可以将其分解为多个运行/调用),且范围内的每个fd都设置为events成员0.以0超时在数组上调用poll,并在每个成员的revents中查找POLLNVAL标志.这将告诉您,只有一个系统调用而不是每个fd一个系统调用,在一组潜在的fds中哪些无效.

I now have a better way to do it. After getting the rlimit, make a large array of struct pollfd (as large as the limit if possible; otherwise you can break it down into multiple runs/calls) with each fd in the range and the events member set to 0. Call poll on the array with 0 timeout, and look for the POLLNVAL flag in the revents for each member. This will tell you which among a potentially-huge set of fds are invalid with a single syscall, rather than one syscall per fd.

这篇关于从C代码获取当前使用的文件描述符的计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆