I looked at the following code in one of our internal libraries, and I'm trying to understand the behavior that it showed:
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; }
After calling GetFD again with the corresponding CloseFD, the entire dll will no longer be able to execute any input / output file. I wrote a tester program and found that I can get GetFD 509 times, but there will be an error 510th time.
Using Process Explorer, the number of pens has not increased.
So, it seems that the dll is reaching the limit for the number of open files; setting _setmaxstdio(2048) increases the time we can call GetFD. Obviously, close () works just fine.
After a bit of searching, I replaced the fopen() call with:
long GetFD(long* fd, const char* fileName, const char* mode) { *fd = (long)open(fileName, 2); if (*fd < 0) return -1; return 0; }
Now, repeatedly calls GetFD / CloseFD.
What's going on here?
source share