Is there a reason fopen () will not work after a few hundred open?

Hey, for this piece of code, the person who wrote the system transfers data between processes using text files. I have loops that look (for all purposes and tasks) as follows:

while (true) { //get the most up-to-date info from the other processes pFile = fopen(paramsFileName, "r"); // Do a bunch of stuff with pFile Sleep(100); } 

This will work several hundred times, but for some reason it will return NULL after some time, although it has already opened the same file path several hundred times already! I double-checked that the file exists and has data in it when fopen returns NULL, and tried to put a delay / retry in it.

What can you think of this?

+7
c ++ fopen
source share
5 answers

You are violating the file / file limit for your OS. It should work forever if you execute fclose (pFile) in your loop.

+13
source share

You really want to check your return codes. I suspect that perror / strerror with the correct error will report that you have exceeded the file descriptor limit.

Try something similar and see if you have a good error message.

 FILE* f = fopen(filename); if (NULL == f) { fprintf(stderr, "Could not open: %s. %s\n", filename, strerror(errno); } 
+5
source share

Why are you doing like that? Two ways to deal with this

 while (true) { //get the most up-to-date info from the other processes pFile = fopen(paramsFileName, "r"); // Do a bunch of stuff with pFile fclose(pFile); // Sleep(100); } 

or Move the fopen call to the outside of the loop

 //get the most up-to-date info from the other processes pFile = fopen(paramsFileName, "r"); while (true) { // Do a bunch of stuff with pFile Sleep(100); } fclose(pFile); 

Not surprisingly, you push the OS limit on the number of open files, constantly calling fopen in your case ...

+2
source share

Try counting the number of times the file was opened before the crash.

In addition, it is possible that the OS opens a file for scanning, which blocks the fopen function, returning null, since it failed to open the file.

0
source share

I assume the thread is running in this loop, and pFile is sent to this thread, leaving it for this thread to close the file.

not the best way to code, and if possible, look at the pFile packaging in a smart / shared pointer that fclose will call when the reference count drops to zero (find this design pattern if you are not familiar with it).

just enter, you have to make sure that anyone even gets a pointer to pFile fclose calls on it (do not call fclose on it from the main thread if another thread should work on it).

hope this helps.

btw, '' in FILE, tells me that this is C ++ code (java does not have '*' types near it).

0
source share

All Articles