Question

After looking into flock I'm a bit confused. Basically there are two forms:

flock [options] <file|directory> <command> [command args]
flock [options] <file descriptor number>

Now if I want to use the second form I need to use exec 200<> file. Then I lock the file with flock 200.

Now I prevented my script from mutilating file because it needs to acquire the lock before doing so. Still why did I have to create the descriptor first? I can operate on file perfectly fine without using that descriptor.

So why am I forced to create a descriptor?

Was it helpful?

Solution

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.

OTHER TIPS

The flock(2) system call -- and therefore the flock command -- can only lock open files while they're open. Once the file handle is closed, the lock is released.

Since all open file handles are closed when the command exit, there's no way to run flock filename to lock a file.

The file either has to be opened in advanced so that it's not closed when flock exits, or it can be opened by flock and operated on by a command that flock invokes, until the command and flock exits, releasing the lock.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top