I have a function which loops through the directories in the proc file system. This function then greps a process name to find its PID and returns this PID to the calling function.
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.