I\'m slowly writing a specialized web server application in C++ (using the C onion http server library and the JSONCPP library for JSON serialization, if t
My solution to this problem is derived from this answer: https://stackoverflow.com/a/19749019/5899976
I've only tested it with GCC 4.8.5.
#include // for strerror()
#include // for std::cerr
#include
#include
extern "C" {
#include
#include // for flock()
}
// Atomically increments a persistent counter, stored in /tmp/counter.txt
int increment_counter()
{
std::fstream file( "/tmp/counter.txt" );
if (!file) file.open( "/tmp/counter.txt", std::fstream::out );
int fd = static_cast< __gnu_cxx::stdio_filebuf< char > * const >( file.rdbuf() )->fd();
if (flock( fd, LOCK_EX ))
{
std::cerr << "Failed to lock file: " << strerror( errno ) << "\n";
}
int value = 0;
file >> value;
file.clear(); // clear eof bit.
file.seekp( 0 );
file << ++value;
return value;
// When 'file' goes out of scope, it's closed. Moreover, since flock() is
// tied to the file descriptor, it gets released when the file is closed.
}