Reputation: 69
I have a Bash script that needs to lock a file for exclusive read/write while it runs. During this time, any other copies of the same script running should hang until the lock is released (which should be pretty quickly).
#!/bin/bash
trap "rm -f /tmp/.lock; exit" 0 1 2 3 15
(
flock -x 100
# Stuff happens here...
) 100>/tmp.lock
This works, somewhat. But not in these conditions:
At this point, I get the error:
rm: cannot remove '/tmp/.lock': Text file busy
I assume I'm totally wrong on how I'm cleaning things up with the trap, so any help would be much appreciated. Thanks!
Upvotes: 0
Views: 1483
Reputation: 295618
DO NOT EVER try to "clean up" flock-style lockfiles whenever it is possible that any program holding that lock could be running or attempting to run.
Keep in mind that locks are held on inodes, not filenames. Deleting a directory entry decouples the inode previously at that location from its name, allowing that name to then refer to a different inode.
Consider the following scenario:
Flock-file lockfiles should be considered mappings from filesystem namespace into file-locking namespace. These mappings do not need to be, and should not be, "cleaned up". You may wish to consider whether your operating system's filesystem hierarchy standard provides a places for such files to live, such as /var/lock
, or somewhere on tmpfs
(where "cleanup" will happen implicitly -- and safely -- on reboot).
Upvotes: 5