bash mutex - aragorn/home GitHub Wiki
Q - bash script μμ mutex λλ semaphore λ₯Ό μ΄μ©νλ €λ©΄ μ΄λ»κ² νλ κ²μ΄ μ’μμ§?
A - ν¬κ² μΈ κ°μ§ λ°©λ²μ΄ μλ€.
mkdir(1)
μ μ΄μ©νλ λ°©λ²flock(1)
μ μ΄μ©νλ λ°©λ² - util-linux ν¨ν€μ§μ ν¬ν¨lockfile(1)
μ μ΄μ©νλ λ°©λ² - procmail ν¨ν€μ§μ ν¬ν¨
flock(1)
λ₯Ό μ¬μ©νλ κ²μ΄ μΌλ°μ μΌλ‘ μ’μ 보μ΄λλ°, μ€ν¬λ¦½νΈκ° λΉμ μ μ’
λ£ν κ²½μ°, μ΄λ»κ² νλνλμ§ μ’ λ νμΈν νμκ° μλ€. flock(1)
μ κ²½μ°, ( ... ) λ‘ bash μ½λλ₯Ό λΈλμΌλ‘ κ°μΈμΌ νλ μ μ½μ΄ μλ€. μ΄λ¬ν μ μ½ λλ¬Έμ μ½λ κΈΈμ΄κ° κΈ΄ κ²½μ°, ν¨μλ μΈλΆ λͺ
λ ΉμΌλ‘ λΆλ¦¬ν΄μΌ κ°λ
μ±μ ν보ν μ μλλ°, μ΄μ λν μΈλ§ν μμ λ₯Ό λ§λ€ νμκ° μλ€.
μ°Έκ³ μλ£
- http://jdimpson.livejournal.com/5685.html
- http://unix.stackexchange.com/questions/70/what-unix-commands-can-be-used-as-a-semaphore-lock
- http://stackoverflow.com/questions/169964/how-to-prevent-a-script-from-running-simultaneously
- http://stackoverflow.com/questions/1715137/the-best-way-to-ensure-only-1-copy-of-bash-script-is-running
#!/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`"
LOCKFD=99
# PRIVATE
_lock() { flock -$1 $LOCKFD; }
_no_more_locking() { _lock u; _lock xn && rm -f $LOCKFILE; }
_prepare_locking() { eval "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.