Skip to content

Instantly share code, notes, and snippets.

@ncopa
Created October 9, 2014 14:46
Show Gist options
  • Save ncopa/ab91578e59be530d9579 to your computer and use it in GitHub Desktop.
Save ncopa/ab91578e59be530d9579 to your computer and use it in GitHub Desktop.
claim_lock()
{
mkdir -p "$LOCK_BASEDIR"
_setlockfd $1
# The locking strategy is identical to that from with-lock-ex(1)
# from chiark-utils, except using flock. It has the benefit of
# it being possible to safely remove the lockfile when done.
# See below for a correctness proof.
local rightfile
while true; do
eval "exec $_lockfd<>$_lockfile"
flock -x $_lockfd || return $?
# We can't just stat /dev/stdin or /proc/self/fd/$_lockfd or
# use bash's test -ef because those all go through what is
# actually a synthetic symlink in /proc and we aren't
# guaranteed that our stat(2) won't lose the race with an
# rm(1) between reading the synthetic link and traversing the
# file system to find the inum. Perl is very fast so use that.
rightfile=$( perl -e '
open STDIN, "<&'$_lockfd'" or die $!;
my $fd_inum = (stat STDIN)[1]; die $! unless defined $fd_inum;
my $file_inum = (stat $ARGV[0])[1];
print "y\n" if $fd_inum eq $file_inum;
' "$_lockfile" )
if [ x$rightfile = xy ]; then break; fi
# Some versions of bash appear to be buggy if the same
# $_lockfile is opened repeatedly. Close the current fd here.
eval "exec $_lockfd<&-"
done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment