What is the difference between lockf and fcntl:
On many systems, the library routine lockf() is just a wrapper around fcntl() . That is, lockf offers a subset of the functions that fcntl does.
Source
But on some locking systems, fcntl and lockf completely independent.
Source
Since it is implementation dependent, be sure to use the same convention. Therefore, either always use lockf from both processes, or always use fcntl. There is a good chance that they will be interchangeable, but it is safer to use the same one.
Which one you choose does not matter.
Some notes on mandatory and advisory locks:
Unix / linux locking is advisory by default, which means that other processes do not need to follow the established locking rules. Therefore, it doesnβt matter how you block if your cooperative processes also use the same convention.
Linux supports mandatory locking, but only if your file system is mounted with the option turned on and special file attributes set. You can use mount -o mand to mount the file system and set the file attributes gx,g+s to enable mandatory locks, then use fcntl or lockf . For more information on how mandatory locks work, see here .
Note that locks do not apply to a single file, but to an inode. This means that 2 file names that point to the same file data will have the same lock status.
On Windows, on the other hand, you can actively open a file, and this will completely block other processes. Even if they want it. Ie, locks are required. The same goes for Windows and file locks. Any process with an open file with the appropriate access can block part of the file, and no other process can access this part.
How forced locks work on Linux:
As for mandatory locks, if a process locks a region of a file with a read lock, then other processes are allowed to read, but not write to this region. If a process locks a region of a file with write lock, then other processes are not allowed to read or write to the file. What happens when a process is not allowed to access part of the file depends on whether O_NONBLOCK is O_NONBLOCK or not. If the lock is set, it will wait for the operation to complete. If the lock is not set, you will receive an EAGAIN error EAGAIN .
NFS Warning:
Be careful if you use lock commands on an NFS mount. The behavior is undefined, and the implementation varies widely, whether to use only local locking or to support remote locking.