File locks are crucial for synchronizing access to files among multiple processes in C++. On Linux, you can use the POSIX `flock` or `fcntl` APIs to implement file locking. Below is an example demonstrating the use of `fcntl` for file locks in C++.
#include
#include
#include
#include
#include
int main() {
const char* filepath = "example.txt";
int fd = open(filepath, O_CREAT | O_RDWR, 0666);
if (fd == -1) {
std::cerr << "Error opening file." << std::endl;
return 1;
}
struct flock lock;
lock.l_type = F_WRLCK; // Write lock
lock.l_whence = SEEK_SET;
lock.l_start = 0;
lock.l_len = 0; // Lock the whole file
// Try to acquire the lock
if (fcntl(fd, F_SETLK, &lock) == -1) {
std::cerr << "File is already locked." << std::endl;
close(fd);
return 1;
}
// File is locked, perform operations...
std::cout << "File is locked. Performing operations..." << std::endl;
// Simulate some file operations
sleep(10); // Simulate time-consuming processing
// Unlock
lock.l_type = F_UNLCK; // Unlock
fcntl(fd, F_SETLK, &lock);
std::cout << "File is unlocked." << std::endl;
close(fd);
return 0;
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?