c_cpp 在给定pid的情况下计算打开文件描述符的实用程序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 在给定pid的情况下计算打开文件描述符的实用程序相关的知识,希望对你有一定的参考价值。
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define procDir "/proc"
#define defaultDelay 60
// Build: /opt/gcc-6/bin/gcc -m64 -lumem -Wall -o countfds ./countfds.c
/*
* count_fds: Count number of of entries, each of which represents
* an open file descriptor in directory by name in `path`.
*/
static int count_fds(const char *path) {
struct dirent *dirp;
DIR *dp;
int nfds = 0;
if ((dp = opendir(path)) == NULL) {
perror("failed to open fd dir for process");
return -1;
}
do {
if ((dirp = readdir(dp)) != NULL) {
if ((strcmp(".", dirp->d_name) == 0) ||
(strcmp("..", dirp->d_name) == 0)) {
continue;
}
nfds++;
}
} while (dirp != NULL);
return nfds;
}
static void lookup(long pid)
{
DIR *dp;
struct dirent *dirp;
char p[256];
int ct = 0;
if ((dp = opendir(procDir)) == NULL) {
perror("couldn't open '.'");
return;
}
do {
errno = 0;
if ((dirp = readdir(dp)) != NULL) {
if (strcmp(dirp->d_name, ".") == 0 ||
strcmp(dirp->d_name, "..") == 0) {
continue;
}
(void) sprintf(p, "%s/%s/fd", procDir, dirp->d_name);
if (strtol(dirp->d_name, NULL, 10) != pid)
continue;
ct = count_fds(p);
if (ct < 0) {
(void) fprintf(stderr,
"PID(%ld): failed counting descriptors\n", pid);
} else {
(void) printf("PID(%ld): %d open descriptors\n", pid, ct);
}
return;
}
} while (dirp != NULL);
if (errno != 0)
perror("error reading directory");
else
(void) printf("failed to find %ld\n", pid);
(void) closedir(dp);
return;
}
int main(int argc, char *argv[])
{
long pid;
int i = 1, pids_idx = 0;
long repeat = 0;
long delay = 0;
// Use FD_COUNT_DELAY to control interval between lookups.
if (getenv("FD_COUNT_DELAY")!=NULL) {
delay = strtol(getenv("FD_COUNT_DELAY"), NULL, 10);
delay = delay == 0 ? defaultDelay : delay;
}
if (argv[1][0] == '-' && argv[1][1] == 'c' ) {
if (argv[1][2] == '\0') {
repeat = atol(argv[2]);
i+=2;
} else {
repeat = atol(&argv[1][2]);
i++;
}
}
pids_idx = i;
while (repeat--) {
for (; i < argc; i++) {
pid = strtol(argv[i], NULL, 10);
if (pid < 0 || pid == 0) { // pid must be non-negative and >0 number
continue;
}
lookup(pid);
}
i = pids_idx;
sleep(delay);
}
return (0);
}
以上是关于c_cpp 在给定pid的情况下计算打开文件描述符的实用程序的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp 由14个“+”和14个“ - ”组成的符号三角形.2个同号下面都是“+”,2个异号下面都是“ - ”。在一般情况下,符号三角形的第一行有n个符号。符号三角形问题要求对于给定的n,计算有多少
如何在给定 PID 的情况下隐藏进程的控制台?
linux文件描述符
简单的文件操作
linux如何查找到某一个进程在调用哪些文件
如何查看一个进程中已经打开的文件描述符