Your problem is that you are doing an opendir
in the loop, but never doing a closedir
. That will leak an fd on each iteration of the outer loop.
How-to open and close files in a loop
-
09-10-2022 - |
質問
I have a while
loop that opens (and closes) files in each loop. After some loops I end up in the "Too many open files" problem – but I call close
each time after reading the file's content. Could anyone assist me with this?
for (;;)
{
dir = opendir( "/proc");
while ( (entry = readdir( dir)) != NULL)
{
pid = atoi( entry->d_name);
// Only processes with a "number" are of interest
if ( pid == 0)
continue;
sprintf( fname, "/proc/%d/cmdline", pid);
fd = open( fname, O_RDONLY);
read( fd, line, MAX_LINE);
/* ... */
close( fd);
}
}
解決
所属していません StackOverflow