Managing access to shared resources is a common concern in many applications. When multiple processes or program instances interact with the same file, accidental overwrites or conflicting writes can occur. Traditional approaches often rely on manually checking whether a file already exists before creating it. Such solutions introduce extra logic and may still suffer from race conditions.
Since C++23, provides a safer mechanism through the std::ios::noreplace open mode. When this flag is used while opening an output file stream, the file will be created only if it does not already exist. If the file is present, the opening operation fails immediately. This makes it possible to implement simple file-based locking without additional checks.
The following example shows how an application can create a lock file that prevents multiple instances from running at the same time:
#include <iostream>
#include <fstream>
#include <filesystem>
#include <thread>
int main() {
std::ofstream lock(
"app.lock",
std::ios::out | std::ios::noreplace
);
if (!lock) {
std::cout << "Already running" << std::endl;
return 1;
}
std::cout << "Started with exclusive lock" << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(10)); // Simulate work
lock.close();
std::filesystem::remove("app.lock");
return 0;
}
In this program, the file app.lock is opened with the std::ios::noreplace flag. The stream creation succeeds only if the file does not yet exist. When another instance attempts to run while the file is already present, the stream fails to open and the program detects that another process is active.
If the file is created successfully, the application continues execution and performs its work. The lock file remains in place while the program runs, serving as a signal to other instances. Once the task completes, the file is closed and removed from the filesystem.
Leave a Comment
Cancel reply