Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does _locking() really do?

Looking for answer of this question I found function _locking(). There tells that it Locks or unlocks bytes of a file (actually I can't understand what does this sentence really mean). If someone have experience of using of this function, is it possible to use the function for solving problem described in first question?

like image 578
Mihran Hovsepyan Avatar asked Nov 04 '22 17:11

Mihran Hovsepyan


2 Answers

Quoting the MSDN page you linked:

int _locking(
   int fd,
   int mode,
   long nbytes 
);

The _locking function locks or unlocks nbytes bytes of the file specified by fd. Locking bytes in a file prevents access to those bytes by other processes. All locking or unlocking begins at the current position of the file pointer and proceeds for the next nbytes bytes. It is possible to lock bytes past end of file.

like image 109
orlp Avatar answered Nov 10 '22 17:11

orlp


It simply reserves a range of a file for the exclusive use of the process that acquires the file lock. If a lock call succeeds, another process that tries to read or write that portion of the file will fail. This allow multiple processes to access the same file and update it in a coherent manner. It's kind of like a mutex for a range of a file.

Basically it allows you to update portions of a file atomically, so any other process reading or writing the file will see (or change) either all of the update, or none of it. It also applies to read - you can lock a range of a file that you want to read to prevent another process from changing part of it while you're in the middle of reading it.

But processes can still access other parts of the file without error or delay.

It will not solve the problem in the question you're referring to because _lock() on;t works at a process granularity. If thread A locks a file range, then thread B in that same process can still read/write that range. To prevent another thread in the same process from accessing a file range, the process would have to implement its own internal mechanism for respecting that a file range has been locked by another thread. At least I'm unaware of something that does that in the Win32 API (I suppose there could be something that I don't know about).

like image 23
Michael Burr Avatar answered Nov 10 '22 17:11

Michael Burr