Choose the Right Advisory File Lock on Linux
Two processes can open the same file and both write to it successfully. That is often exactly what Unix applications need, but sometimes the programs are supposed to coordinate: only one worker should update a state file, several readers may share a resource, or a process must avoid changing a byte range while another process is using it. Linux offers several advisory file-locking mechanisms. The confusing part is not how to request a lock. The confusing part is what owns the lock and when that lock disappears.