C(Linux) 中的 fopen 返回“打开的文件太多”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10966392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fopen in C(Linux) returns "Too many open files"
提问by liv2hak
static char filename[128] = "trace.txt";
g_file = fopen(filename, "w");
if(NULL == g_file)
{
printf("Cannot open file %s.error %s\n",filename,strerror(errno));
exit(1);
}
I am trying to open a empty text file named trace.txt in write mode (in my working directory.) The program is creating an empty file trace.txt in my directory.but the check (NULL == g_file) is returning true and it is returning error code 24 (Too many open files.).Any idea why this is.This is the first file I am opening in my program.
我正在尝试以写入模式(在我的工作目录中)打开一个名为 trace.txt 的空文本文件。该程序正在我的目录中创建一个空文件 trace.txt。但是检查 (NULL == g_file) 返回 true 并且它返回错误代码 24(打开的文件太多。)。知道这是为什么。这是我在程序中打开的第一个文件。
Surprisingly the code is creating an empty file in my working directory by the name specified.However the check for null file pointer is succeeding for some reason.? :(
令人惊讶的是,代码在我的工作目录中创建了一个指定名称的空文件。但是由于某种原因,空文件指针的检查成功了。?:(
采纳答案by ugoren
You probably have a file descriptor leak.
If your code keeps opening files, never closing them, you will reach the limit sooner or later, and then fopen
will fail.
您可能有文件描述符泄漏。
如果你的代码不断打开文件,从不关闭它们,你迟早会达到限制,然后fopen
就会失败。
You can check this by printing the file descriptor numbers you get whenever opening a file. If they keep growing, you have a leak.
您可以通过打印每次打开文件时获得的文件描述符编号来检查这一点。如果它们继续增长,则说明存在泄漏。
回答by Shane
This looks like a similar issue to what you're having, but I'm not entirely sure if it will help you solve the problem. Might be worth a look:
这看起来与您遇到的问题类似,但我不完全确定它是否会帮助您解决问题。可能值得一看:
回答by David M. Syzdek
It is most likely due to your system reaching its maximum allowed open file handles.
这很可能是由于您的系统达到了其允许的最大打开文件句柄。
You can easily test this by running the following:
您可以通过运行以下命令轻松测试:
$ dd if=/dev/urandom of=test.dat bs=16 count=1
If you are out of file handles, this should provide the same or similar error.
如果您没有文件句柄,这应该提供相同或类似的错误。
You can trouble shoot this using some of the following commands:
您可以使用以下一些命令解决此问题:
To see the maximum allowed open files:
查看允许的最大打开文件数:
$ cat /proc/sys/fs/file-max
To see the which files are currently open (remember this includes device files, sockets, etc):
要查看当前打开了哪些文件(请记住,这包括设备文件、套接字等):
$ lsof
You can also use lsof
to get a count of open files:
您还可以使用lsof
来获取打开文件的数量:
$ lsof | wc -l
回答by chakra t
Correct, I faced same error message and found that I was trying to close the file in a function but not where it was opened. So I then closed in the function where it was opened, later everything went fine.
正确,我遇到了同样的错误消息,发现我试图在函数中关闭文件,而不是在打开它的地方。所以我然后在打开它的函数中关闭,后来一切正常。