gpt4 book ai didi

c - 如何打开和打印目录中的所有文件

转载 作者:太空宇宙 更新时间:2023-11-04 03:47:46 25 4
gpt4 key购买 nike

我正在编写一个代码来计算当前正在运行的所有进程的 CPU 使用率。正是 Top 命令的作用。我在尝试获取系统中的所有进程 pid 时遇到了一些困难。我知道 pids 在/proc 目录中。谁能帮我一次打开所有文件。或者有什么方法可以将所有 pid 号存储在一个数组中。任何帮助将非常感激。

最佳答案

这可能是您的实现之一(粗略的步骤)。你将不得不做错误实现时的处理和尺寸管理。有关更多信息,您应该引用其他人建议的一些手册/书籍。您还应该了解安全功能,因为某些目录可能没有读取权限。请在实现前尝试理解这些概念。

#define MAX_ENTRY 3000
struct dirent *entry[MAX_ENTRY] = {NULL};
struct stat sb[MAX_ENTRY];
// name = "/proc"
dir = opendir( name);
for(i =0; ; i++) {
entry[i] = readdir(dir);
if (entry[i] == NULL)
break;
}

for(j = 0;j < i ;j++) {
ret = stat( entry[j]->d_name, &sb[j]);
//now check the attribute of sb[j].st_mode to determine whether directory
//or not. in this case /proc directory maintains one directory per process.
//Additionally you may want to check that name contains all numbers not any
//characters to double sure that you are fetching PID of a process not other
// directory maintained by /proc

if(S_ISDIR(sb[j].st_mode)) {
// This should print like 0,1,2,3,4...........You can store it in some
// different dynamic array. Now you can use this list of PID for your
// actual work.
printf("%s\n",entry[j]->d_name);
}

关于c - 如何打开和打印目录中的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22990120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com