fopen问题-打开文件过多 [英] fopen problem - too many open files

查看:260
本文介绍了fopen问题-打开文件过多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在Win XP上运行的多线程应用程序.在某个阶段,线程之一无法使用fopen函数打开现有文件. _get_errno函数返回EMFILE,这意味着打开的文件太多.没有更多的文件描述符.我的平台的FOPEN_MAX为20._getmaxstdio返回512.我用WinDbg进行了检查,发现大约有100个文件处于打开状态:

I have a multithreaded application running on Win XP. At a certain stage one of a threads is failing to open an existing file using fopen function. _get_errno function returns EMFILE which means Too many open files. No more file descriptors are available. 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

fopen失败的原因是什么?

What is the reason that fopen fails ?

我编写了简单的单线程测试应用程序.该应用程序可以打开510个文件.我不明白为什么这个应用程序比多线程应用程序可以打开更多文件.可能是由于文件句柄泄漏引起的吗?

I wrote simple single threaded test application. This app can open 510 files. I don't understand why this app can open more files then multithreaded app. Can it be because of file handle 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); 
        } 
    } 
}

推荐答案

我认为在win32中,所有crt函数最终都将使用下面的win32 API结束.因此,在这种情况下,很可能它必须使用win32的CreateFile/OpenFile.现在,CreatFile/OpenFile api不仅适用于文件(文件,目录,通信端口,管道,邮件插槽,驱动器卷等).因此,在实际的应用程序中,取决于这些资源的数量,您的最大打开文件数可能会有所不同.由于您对应用程序的描述不多.这是我的第一个猜测.如果时间允许,请通过 http://blogs. technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx

I think in win32 all the crt function will finally endup using the win32 api underneath. So in this case most probably it must be using CreateFile/OpenFile of win32. Now CreatFile/OpenFile api is not meant only for files (Files,Directories,Communication Ports,pipes,mail slots,Drive volumes etc.,). So in a real application depending on the number these resources your max open file may vary. Since you have not described much about the application. This is my first guess. If time permits go through this http://blogs.technet.com/b/markrussinovich/archive/2009/09/29/3283844.aspx

这篇关于fopen问题-打开文件过多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆