lock
is a simple implementation of advisory file locking using fcntl(). (In fact, years ago, I wrote a practically identical command-line utility, which executed a single command or script while holding a lock on the specified file.)
fcntl()
locks work for remote filesystems if the servers have the support enabled. In particular, Samba and NFS servers on Linux definitely do have the capability. On NFS it is usually either misconfigured or outright disabled, so hardlink- or lock directory -based locking schemes are more common. Sadly.
Technically, fcntl()
locks are not file locks, but record locks: any byte range in the file can be separately locked, even by different processes. The most common use is to lock the entire file (by specifying zero start and length, so the lock will apply even if the file is appended to). The lock
command does exactly that if you omit both the hex-start
and hex-length
parameters.
If you do specify the hex-start
to lock
, it refers to the offset where the lock region starts. If you omit or use zero hex-length
, then the lock applies to the rest of the file, even if the file is appended to, or truncated. If you also specify hex-length
, then the lock applies to offsets [hex-start
, hex-start
+hex-length
). The hex-
prefix obviously refers to the values being specified in hexadecimal.
The locks are advisory, because they do not prevent any kind of access to the file. Every application needs to call fcntl()
, to obtain an advisory lock on the file; if the desired lock would conflict with other locks on the same file, the call will block (F_SETLKW
) or fail (F_SETLK
).
Questions?