【问题标题】:opendir: Too many open filesopendir:打开的文件太多
【发布时间】:2012-05-09 07:18:04
【问题描述】:

我编写此代码以打印/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);
}

当我运行它时。

不仅打印一些文件的路径,还打印一些错误信息:

opendir: Too many open files

我看了man 3 opendir,然后意识到,我打开的文件太多了。

我想知道,如何关闭它?以及如何纠正这个程序

【问题讨论】:

    标签: c linux file gnu opendir


    【解决方案1】:

    当您完成对目录内容的迭代时,您可能应该使用closedir

    此外,您可能希望将目录列表读入数组,关闭目录,然后在数组上递归。这可能有助于遍历非常深的目录结构。

    【讨论】:

      【解决方案2】:

      运行

      cat /proc/sys/fs/file-nr

      它有什么作用?
      输出格式为:(分配的文件处理程序的数量)-(已分配但未使用的文件处理程序的数量)-(文件处理程序的最大数量)

      如果您获得更多已分配但未使用的文件处理程序,则意味着您必须关闭 @Matthew Iselin 提到的目录。
      您还可以更改系统限制。

      更多关于更改系统限制Can be found here的信息。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-07-18
        • 2019-10-30
        • 2011-01-03
        • 2011-08-05
        • 2014-03-31
        • 2017-03-03
        相关资源
        最近更新 更多