Is the file guaranteed to be opened for reading without any errors after returning from the :: close () stream?

I need my code (C ++, on linux) to call the second executable file, after writing the output file, which is read by the second program. Is the naive approach

std::ofstream out("myfile.txt"); // write output here out.close(); system("secondprogram myfile.txt"); 

suffer from a potential race condition, where, despite the fact that out.close () is executed, the file cannot be read immediately by secondprogram ? If so, what is the best practice to solve this problem?

Three notes:

  • If it depends on the file system, I'm interested in behavior on ext3 and tmpfs.
  • It is clear that there are other reasons (file permissions, etc.) why the second program may not open the file; I'm just interested in the potential of the race.
  • The hard-coded file name in the above example is for simplicity; I'm actually using mkstemp .
+7
source share
3 answers

There is a potential failure mode that I skipped earlier: you seem to have no way to recover when the file cannot be opened by secondprogram . The problem is not that the file may be locked / incompatible after returning close() , but this other program, completely unrelated to yours, may open the file between close() and system() (say, an AV scanner, someone then grep through the directory containing the file, the backup process). If this happens, the secondprogram will fail, even if your program behaves correctly.

TL / DR: despite the fact that everything works as expected, you should consider the case where the secondprogram may not open the file!

+1
source

After closing the file, all recorded data will be cleared of the buffers of the ofstream object (since at this moment you can destroy it without any risk of losing all data and actually close the file internally by the destructor, if necessary). This does not mean that the data at this stage will be physically located on the disk (this probably will not be due to the caching behavior of the OS disk drivers), but any program running in the same OS will be able to read the file sequentially (since the OS will read from cached data). If you need to flush OS buffers to disk (which is not required for your second program to read the input file correctly), you might want to look at the sync() function in <unistd.h> .

+3
source

According to cplusplus.com, the function will return when all data has been written to disk. Therefore, there should be no race condition.

0
source

All Articles