Too many open files

Hi All,

    in my controller application, I need to write daily log files to compact flash for later uploading, there is a log file stored in CF that I can not open with fopen function and then I used the command sin fd and found that this file owned the file decriptor range from 10 to 995, I would like to know in wich case it produced this issue and how to prevent it to be happened.

   thanks many in advance.

Regards,
shilunz

naive question:

are you using fclose() after you processed the file?

after each writing whole data to log file, the fclose function is called, actually it has been running well for one month, and this issue happened at the same time in all the five tested controller. I am not very sure whether it related to the power trip on that day. I would like to know how to find this issue and resolve it.

thanks.

What to you mean by fopen cannot open, what is the value of errno. My guess is you think you are using fclose but you are probably not or something goes wrong while calling fclose.

fds are not limited to ‘files’. They can be any ‘connection’.

Are you doing raw ConnectAttach()'s elsewhere?

the error code is 24
WriteFile(char *name)
{
fp=fopen()

}
ReadFile(char *name)
{
fp=fopen() //error here

}

thread1()
{
if(triggered)
WriteFile()
}
thread1()
{
if(comm free)
ReadFile()
}

mutex used in thread.

thanks.

And where is the fclose? Error 24 is “too many open files”…

fclose() is after fread() and fwrite()

Can you post the actual code you are using and not pseudo code.

int WriteLogFile(unsigned char *buf,unsigned int len,unsigned char type)
{

unsigned int i;
char r=0;


FILE *fp;
char trn_type;

i=0;
trn_type=type;

fp=OpenFile(&Log[type],"ab+r");
if(fp==NULL)
{
	
	CloseFile(fp);
	return -1; 
}			
else
{
		
	WriteFile(fp,offset,buf,len);
	tTRN[trn_type].offset+=len;
	
	CloseFile(fp);		
}
return r;			

};

int ReadLogFile(unsigned char *buf,unsigned int len,unsigned char type,unsigned int offset)
{
char r=0;

FILE *fp;
char trn_type;
	
trn_type=type;

fp=OpenFile(&Log[type],"r");
if(fp==NULL)
{
	
	CloseFile(fp);
	return -1; 
}			
else
{
	ReadFile(fp,offset,buf,len);
	CloseFile(fp);		
}
return r;			

};
int ReadFile(FILE *fp,long offset,unsigned char *buf,int len)
{
int n;

if( fp != NULL )
{
   
	fseek(fp,offset,SEEK_SET);
	n=fread(buf, 1, len, fp );
	if(ferror(fp))
		return -1;    		    
}
else
	return -1;
				
return n;

};

int WriteFile(FILE *fp,long offset,unsigned char *buf,int len)
{
int n;

if( fp != NULL )
{
   
	fseek(fp,offset,SEEK_SET);
	n=fwrite(buf, 1, len, fp );
	
	if(ferror(fp))
		return -1;    		    
}
else
	return -1;  
					
return 0;

};

You are making this difficult ;-) where are the OpenFile and CloseFile functions

Are you checking the return value of fclose()?
Perhaps it just failes for some reason…