简体   繁体   English

opendir:打开的文件太多

[英]opendir: Too many open files

I write this code to print all files in /home/keep with absolution path: 我编写以下代码来打印/home/keep具有绝对解决方案路径的所有文件:

#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. 我读了man 3 opendir ,然后意识到,我打开了太多文件。

I do want to know, how to close it? 我想知道,如何关闭它? and how to correct this program 以及如何纠正此程序

You should probably use closedir when you finish iterating through a directory's contents. 完成对目录内容的循环访问时,可能应该使用closedir

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. 这可能有助于遍历非常深的目录结构。

Run

cat /proc/sys/fs/file-nr 猫/ 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. 如果获得更多数量的已分配但未使用的文件处理程序,则意味着您必须关闭@Matthew Iselin提到的目录。
You can also change system limit. 您还可以更改系统限制。

More info about changing system limit Can be found here . 有关更改系统限制的更多信息,请参见此处

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

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