Forked from przemoc/lockable_script_boilerplate.sh
Last active
March 26, 2018 21:39
-
-
Save jmorahan/64776a1afc1615373544 to your computer and use it in GitHub Desktop.
Lockable script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
## Copyright (C) 2009 Przemyslaw Pawelczyk <[email protected]> | |
## License: GNU General Public License v2, v3 | |
# | |
# Lockable script boilerplate | |
### HEADER ### | |
LOCKFILE="/var/lock/$(basename "$0")" | |
# PRIVATE | |
_lock() { | |
while flock -"$1" "$LOCKFD"; do | |
INODE_FD="$(stat -Lc%i "/proc/$$/fd/$LOCKFD" 2>/dev/null)" | |
INODE_FS="$(stat -c%i "$LOCKFILE" 2>/dev/null)" | |
[ "$INODE_FD" = "$INODE_FS" ] && return 0 || exec {LOCKFD}>"$LOCKFILE" | |
done | |
return 1 | |
} | |
_no_more_locking() { _lock u; _lock xn && rm -f "$LOCKFILE"; } | |
_prepare_locking() { exec {LOCKFD}>"$LOCKFILE"; trap _no_more_locking EXIT; } | |
# ON START | |
_prepare_locking | |
# PUBLIC | |
exlock_now() { _lock xn; } # obtain an exclusive lock immediately or fail | |
exlock() { _lock x; } # obtain an exclusive lock | |
shlock() { _lock s; } # obtain a shared lock | |
unlock() { _lock u; } # drop a lock | |
### BEGIN OF SCRIPT ### | |
# Simplest example is avoiding running multiple instances of script. | |
exlock_now || exit 1 | |
# Remember! Lock file is removed when one of the scripts exits and it is | |
# the only script holding the lock or lock is not acquired at all. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment