Question

How can I block a file on Windows using C++ in a blocking fashion? By blocking I mean... a lock is requested and if the file is locked it will wait until it is unlocked, once the file is unlocked by another system process than the execution resumes.

P.S.: If there's some kind of cross platform solution I'd prefer it.

Was it helpful?

Solution

By default, LockFileEx blocks until the lock can be acquired (although you can tell it not to with LOCKFILE_FAIL_IMMEDIATELY).

Clearly this isn't cross-platform.

Update

This horrible code sample illustrates that it works (you'll probably need to change the filename in CreateFile from "lockBlock.cpp"). Run one instance of the program and it will acquire the lock. Run a second instance and it will block. Press <enter> in the first instance to release the lock, and the second instance will unblock and acquire the lock.

int _tmain(int argc, _TCHAR* argv[])
{
    HANDLE hFile = ::CreateFileA("lockBlock.cpp", GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
    OVERLAPPED overlapped;
    memset(&overlapped, 0, sizeof(overlapped));
    const int lockSize = 10000;
    printf("Taking lock\n");
    if (!LockFileEx(hFile, LOCKFILE_EXCLUSIVE_LOCK, 0, lockSize, 0, &overlapped))
    {
        DWORD err = GetLastError();
        printf("Error %i\n", err);
    }
    else
    {
        printf("Acquired lock\n");
        getchar();
        UnlockFileEx(hFile, 0, lockSize, 0, &overlapped);
        printf("Released lock\n");
    }
    return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top