How do I use file locks on Linux in C++?

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

File locks C++ Linux fcntl POSIX