【发布时间】:2010-04-07 12:40:14
【问题描述】:
我在我们的一个内部 dll 中遇到了以下代码,我试图了解它所显示的行为:
long GetFD(long* fd, const char* fileName, const char* mode)
{
string fileMode;
if (strlen(mode) == 0 || tolower(mode[0]) == 'w' || tolower(mode[0]) == 'o')
fileMode = string("w");
else if (tolower(mode[0]) == 'a')
fileMode = string("a");
else if (tolower(mode[0]) == 'r')
fileMode = string("r");
else
return -1;
FILE* ofp;
ofp = fopen(fileName, fileMode.c_str());
if (! ofp)
return -1;
*fd = (long)_fileno(ofp);
if (*fd < 0)
return -1;
return 0;
}
long CloseFD(long fd)
{
close((int)fd);
return 0;
}
在使用适当的 CloseFD 重复调用 GetFD 后,整个 dll 将不再能够进行任何文件 IO。我写了一个测试程序,发现我可以GetFD 509次,但是第510次会出错。
使用 Process Explorer,Handles 的数量没有增加。
看来 dll 已达到打开文件数的限制;设置_setmaxstdio(2048) 确实增加了我们调用GetFD 的次数。显然,close() 工作得很好。
经过一番搜索,我将fopen() 调用替换为:
long GetFD(long* fd, const char* fileName, const char* mode)
{
*fd = (long)open(fileName, 2);
if (*fd < 0)
return -1;
return 0;
}
现在,重复调用 GetFD/CloseFD 有效。
这里发生了什么?
【问题讨论】: