Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Lock File Windows Blocking Mode

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.

like image 768
petersaints Avatar asked Mar 25 '26 00:03

petersaints


1 Answers

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;
}
like image 182
arx Avatar answered Mar 26 '26 14:03

arx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!