cfile-ioposixflock

What Happens to POSIX File Lock When the Underlying File is Overwritten


Title says it all. Suppose I have a file which multiple processes want to modify using my library. A traditional means of preventing corruption is to use flock or similar to place an advisory lock on the file. Each process attempts to open the file and acquire the lock; blocking or erroring if the lock cannot be obtained.

Now, suppose I want to insert a line into the middle of the file. The canonical, "safe" way to do this is a second file which is then moved over the first once all of the writing is done.

In the above case, what happens to any existing file locks on the original file? Are they preserved since the underlying struct dirent doesn't change (excluding the creation / modification timestamps)? What happens to any other process blocked on flock when this happens? The flock manpage is mute on these topics, unfortunately.

Finally, if the above operations result in the lock being lost, what is a good means of preventing concurrent modification in lieu of flock?


Solution

  • Locks are associated with the inode, not the filename. So if you have locks on file1, and then do mv file1.new file1, the inode of the old file1 is unchanged (if there are other hard links, they still reference the original file), and the filename file1 now points to the inode of file1.new.

    As a result, all the file locks still persist on the original file. Even if there are no filenames referring to it, the file contents continue to exist as long as there are any open file handles pointing to it.