flock-ing a C++ ifstream on Linux (GCC 4.6)

后端 未结 4 365
终归单人心
终归单人心 2021-01-13 04:39

context

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

4条回答
  •  不思量自难忘°
    2021-01-13 04:51

    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.
    }
    

提交回复
热议问题