質問

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);
    }
}
役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top