我有一个在 Win XP 上运行的多线程应用程序。在某个阶段,一个线程无法使用 fopen 函数打开现有文件。_get_errno 函数返回 EMFILE,这意味着打开的文件太多。没有更多的文件描述符可用。我的平台的 FOPEN_MAX 是 20。_getmaxstdio 返回 512。我用 WinDbg 进行了检查,发现大约有 100 个文件处于打开状态:
788 Handles
Type Count
Event 201
Section 12
File 101
Port 3
Directory 3
Mutant 32
WindowStation 2
Semaphore 351
Key 12
Thread 63
Desktop 1
IoCompletion 6
KeyedEvent 1
fopen 失败的原因是什么?
编辑:
我编写了简单的单线程测试应用程序。这个应用程序可以打开 510 个文件。我不明白为什么这个应用程序可以打开比多线程应用程序更多的文件。可能是因为文件句柄泄漏吗?
#include <cstdio>
#include <cassert>
#include <cerrno>
void main()
{
int counter(0);
while (true)
{
char buffer[256] = {0};
sprintf(buffer, "C:\\temp\\abc\\abc%d.txt", counter++);
FILE* hFile = fopen(buffer, "wb+");
if (0 == hFile)
{
// check error code
int err(0);
errno_t ret = _get_errno(&err);
assert(0 == ret);
int maxAllowed = _getmaxstdio();
assert(hFile);
}
}
}