Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open file exclusively/lock file

I want to lock an existing file to prevent usage (read and write) from another process. That is, any subsequent attempt to open the file by this process or any other process should fail with an 'access denied' error.

The CreateFile WINAPI function has a dwShareMode parameter which does exactly that, I'm looking for similar functionality while still being able to use QFile.

like image 807
fpdragon Avatar asked Aug 10 '12 07:08

fpdragon


People also ask

How can I open a locked file?

Right-click on the file. In the menu that appears, select Lock File. To unlock, right-click the file and select Unlock File.

How do I turn off file lock?

Procedure. In the administrative console, click Servers > Server Types > WebSphere application servers > server_name > [Container Settings] Container Services > Transaction Service. Clear the Enable file locking check box. Click Apply or OK.

What are shared and exclusive file locks?

An exclusive or write lock gives a process exclusive access for writing to the specified part of the file. While a write lock is in place, no other process can lock that part of the file. A shared or read lock prohibits any other process from requesting a write lock on the specified part of the file.


2 Answers

One way I found is to use LockFile on the underlying OS handle after you have already opened your file.

Note that LockFile has a slightly different behavior - subsequent attempts to open succeed, but actual reading or writing will fail with ERROR_LOCK_VIOLATION.

#include <windows.h>
#include <io.h>
bool lockFile(QFile *file) {
    return (bool) LockFile((HANDLE) _get_osfhandle(file->handle()), 0, 0, -1, -1);
}
void test() {
    QFile f("test.txt");
    f.open(QIODevice::ReadOnly);
    lockFile(&f);
}
like image 91
sashoalm Avatar answered Sep 18 '22 16:09

sashoalm


Have you tried saving (overwriting) with Notepad++? I believe the correct behavior is that it wont let you write to the same filename. Opening (reading) is not enforceable; writing is the real test.

like image 38
Preet Kukreti Avatar answered Sep 19 '22 16:09

Preet Kukreti