I have a multi-threaded application running on Win XP. At a certain point, one of the threads cannot open an existing file using the fopen function. The _get_errno function returns EMFILE, which means too many open files. No more file descriptors. FOPEN_MAX for my platform is 20. _getmaxstdio returns 512. I checked this with WinDbg and I see that about 100 files are open:
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
What is the reason for the failure of fopen?
EDIT:
I wrote a simple single-threaded test application. This application can open 510 files. I do not understand why this application can open more files, and then a multi-threaded application. Could this be due to file descriptor leaks?
#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); } } }
source share