One of the primary advantages of using flock()
-- or the fcntl(LOCK_EX)
mechanism it's closely related to -- over more traditional locking mechanisms is that there's no need to perform cleanup on reboot or other unclean shutdown scenarios.
This is possible because the lock is attached via a file descriptor; when that file descriptor is closed -- whether by a graceful shutdown, a SIGKILL or a power loss -- the lock is no longer held.
When you use the underlying flock()
syscall -- which the flock
command-line tool invokes -- that lock lasts as long as your file descriptor does. Consequently, if you want a single lock on a file to be open for the duration of multiple commands, you need a descriptor to be held through that time period.
If flock
didn't have this design requirement, it would have no way of automatically closing and cleaning up locks whenever the processes associated with them exit. This would make flock
far less useful.