opendir: Too many open files

…衆ロ難τιáo~ 提交于 2019-12-11 05:14:31

问题


I write this code to print all files in /home/keep with absolution path:

#include <dirent.h>
#include <sys/stat.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

void catDIR(const char *re_path);

int main(int argc, char *argv[])
{
    char *top_path = "/home/keep";
    catDIR(top_path);
    return 0;
}

void catDIR(const char *re_path)
{
    DIR *dp;
    struct stat file_info;
    struct dirent *entry;

    if ((dp = opendir(re_path)) == NULL)
    {
        perror("opendir");
        return;
    }
    while (entry = readdir(dp))
    {
        if (entry->d_name[0] == '.')
            continue;

        //get Absolute path
        char next_path[PATH_MAX];
        strcpy(next_path, re_path);
        strcat(next_path, "/");
        strcat(next_path, entry->d_name);

        lstat(next_path, &file_info);

        if (S_ISDIR(file_info.st_mode))
        {
            catDIR(next_path);
        }
        else
        {
            printf("%s/%s\n", re_path, entry->d_name);
        }
    }
    free(dp);
    free(entry);
}

When I run it.

Not only print some file's path, but also print some error message:

opendir: Too many open files

I read man 3 opendir, then realize, I had opened too many files.

I do want to know, how to close it? and how to correct this program


回答1:


You should probably use closedir when you finish iterating through a directory's contents.

Also, you might want to read the directory's listing into an array, close the directory, and then recurse on the array. This might help with traversing very deep directory structures.




回答2:


Run

cat /proc/sys/fs/file-nr

what does it give ?
output format is : (number of allocated file handlers) - (number of allocated but unused file handlers) - (maximum number of file handlers)

If you get more number of allocated but unused file handlers, it means that you've to close directories as mentioned by @Matthew Iselin.
You can also change system limit.

More info about changing system limit Can be found here.



来源:https://stackoverflow.com/questions/10369309/opendir-too-many-open-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!