简体   繁体   English

在proc中遍历目录

[英]Looping through directories in proc

I have a function which loops through the directories in the proc file system. 我有一个循环遍历proc文件系统中目录的函数。 This function then greps a process name to find its PID and returns this PID to the calling function. 然后,此函数会抓取一个进程名称以找到其PID,并将此PID返回给调用函数。

The function seems to work fine but fails in one or two cases while opening some directory(corresponding to a process). 该函数似乎工作正常,但在打开某些目录(对应于一个进程)时在一两种情况下失败。 This is what I am doing. 这就是我在做什么。

 dr = readdir(dp); 

Loop through dr 遍历博士
Check dr type for directory and process name 检查博士类型的目录和进程名称
compare the process name with a string. 将进程名称与字符串进行比较。

 Return PID in case of a match 
 dr = readdir(dp);
 end loop 



main() {
   DIR *d;
   struct dirent *e;

   e=malloc(sizeof(struct dirent));
   d=opendir("/proc");

   while ((e = readdir(d)) != NULL) {
      printf("%d %s\n", e->d_type, e->d_name);
   }

   closedir(d);
}

Presumably the problem is that directories are disappearing before you get to check out the files inside. 大概的问题是,在您检出其中的文件之前,目录已经消失了。 This would mean that a process that was running when you go the directory listing is no longer running when you go to read its process information. 这意味着当您转到目录列表时正在运行的进程在您阅读其进程信息时不再运行。 This is normal and something you'll have to handle (ideally silently) in your application. 这是正常现象,您必须在应用程序中(理想情况下以静默方式)进行处理。

Also, the code snippet you provided definitely does not do what you described above it. 同样,您提供的代码段绝对不会像您在上面描述的那样执行。 Presumably you edited it for simplicity, but in doing so you removed any clues as to what you might be doing wrong. 大概是为了简单起见,您对其进行了编辑,但是这样做却删除了有关您可能做错了什么的任何线索。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM