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:
mkstemp
.ofstream will close files when its destructor is called, i.e. when it goes out of scope.
Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only. Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With