Passing 0
as dwShareMode
argument during CreateFile
call will prevent other processes to obtain a file handle, until current process will call CloseHandle
.
What is the purpose of locking with LockFileEx
then? Only to have ability to lock file after retrieving the handle?
Will CreateFile
with 0
for dwShareMode
without calling LockFileEx
be enough for safety, if there are a lot of multiple processes that try to read-write same file pretty frequently (for example, there is a big chance that 10 processes may try to open and write the same file at the same time)?
Will the next code guarantee the safe concurrency (only one process at once may access the file)?
// There will be tens of instances of the program below, running at the same time
#include <Windows.h>
void updateFileSafe()
{
HANDLE handle = INVALID_HANDLE_VALUE;
while(handle == INVALID_HANDLE_VALUE)
handle = CreateFile(L"path", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
...
CloseHandle(handle);
}
int main()
{
for(;;)
{
updateFileSafe();
Sleep(100);
}
return 0;
}
The share mode of CreateFile
applies to the entire file as a whole, and controls whether or not other processes can have open handles to the file at the same time.
LockFile/Ex
can lock a region of a file to prevent other processes from accessing just that region, even if they have handles open to the file.