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

时间:2014-04-10 13:55:00

标签: c unix

我正在编写一个代码来计算当前正在运行的所有进程的cpu使用情况。正如Top命令所做的那样。我正在努力尝试获取系统中的所有进程pids。我知道pid在/ proc目录中。任何人都可以帮我如何打开所有文件一次。或者有什么方法可以将所有pid数字存储在一个数组中。任何帮助将非常感激。

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

无论如何,你可以打开烟斗并做任何你想做的事情,虽然管道成本很高但你可以在没有任何东西的情况下将它们作为替代品。你可以调整命令并做任何你想做的事。

#include<stdio.h>
void printList(char* pdirname)
{
   if(NULL == pdirname)
   return;

   char command[256];
   sprintf(command,"find %s -maxdepth 1 -type d ",pdirname);

   FILE * fp = popen(command, "r");
   char arr[255];
   while( NULL != fgets(arr,255, fp))
   {
     printf("%s", arr);
   }
}

int main(int argc, char* argv[])
{
if(argc != 2)
{
  printf("wrong input: usage -./a.out <dirname> e.g. :: ./a.out /usr/local \n");
  return 0;
}

printList(argv[1]);

return (0);
}