Reputation: 124
I'm looking for a portable way (linux & Windows) to have a file only modifiable by 1 process and not others in C/C++.
The full requirement is that I want to keep a file only modifiable by 1 running process, as the others should only be able to read it.
The difficulty is that this process uses a vendor library that will fopen/fclose the file many times during its life (tens of seconds).
Thanks
Upvotes: 0
Views: 146
Reputation: 80
You should make use of the "inter process communications"
For instance ,on Windows you could use following code, which makes sure that only one process would be able to write into this file.
int WriteToFile()
{
HANDLE _mutex = CreateMutex(NULL, TRUE, L"__File_Write__");
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
return -1;
}
else
{
//write to file
return 0;
}
}
Upvotes: 1