Chris Johnson
Chris Johnson

Reputation: 10680

Is a file guaranteed to be openable for reading immidiately after ofstream::close() has returned?

I need my code (C++, on linux) to call a second executable, having previously written an output file which is read by the second program. Does the naïve approach,

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

suffer from a potential race condition, where even though out.close() has executed, the file cannot immediately be read by secondprogram? If so, what is the best practice for resolving this?

Three notes:

Upvotes: 7

Views: 508

Answers (3)

us2012
us2012

Reputation: 16253

There is a potential failure mode that I missed earlier: You don't seem to have a way of recovering when the file cannot be opened by secondprogram. The problem is not that the file might be locked/inconsistent after close() returns, but that another program, completely unrelated to yours, might open the file between close() and system() (say, an AV scanner, someone greping through the directory containing the file, a backup process). If that happens, secondprogram will fail even though your program behaves correctly.

TL/DR: Even though everything works as expected, you have to account for the case that secondprogram may not be able to open the file!

Upvotes: 1

Ale
Ale

Reputation: 1819

Once the file has been closed, all the written data is guaranteed to be flushed from the buffers of the ofstream object (because at that point you can destroy it without any risk of losing whatsoever data, and actually closing the file is internally done by the destructor if needed). This does not mean that the data will at this point be physically on the disk (it will probably not, because of caching behavior of the OS disk drivers), but any program running in the same OS will be able to read the file consistently (as the OS will then perform the reading from the cached data). If you need to flush the OS buffers to the disk (which is not needed for your secondprogram to correctly read the input file), then you might want to look at the sync() function in <unistd.h>.

Upvotes: 3

bash.d
bash.d

Reputation: 13207

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

Upvotes: 0

Related Questions