File locks in macOS can be implemented using the `fcntl` function, which allows you to apply advisory locks to files. This is useful for controlling access to files in concurrent programming to ensure that only one process can write to or read from a file at a time, avoiding data corruption.
This example demonstrates how to create a file lock using C++ on macOS:
#include <iostream>
#include <fcntl.h>
#include <cstdio>
#include <unistd.h>
int main() {
const char* filename = "example.txt";
FILE* file = fopen(filename, "w");
if (!file) {
perror("File opening failed");
return EXIT_FAILURE;
}
struct flock lock;
lock.l_type = F_WRLCK; // Write lock
lock.l_whence = SEEK_SET; // Lock starting from the beginning
lock.l_start = 0; // Lock starts from byte 0
lock.l_len = 0; // Lock till the end of the file
// Try to acquire the lock
if (fcntl(fileno(file), F_SETLK, &lock) == -1) {
perror("Failed to acquire lock");
fclose(file);
return EXIT_FAILURE;
}
// Write to the file
fprintf(file, "This file is locked for writing.\n");
// Release the lock
lock.l_type = F_UNLCK; // Unlock
fcntl(fileno(file), F_SETLK, &lock);
fclose(file);
return EXIT_SUCCESS;
}
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?