util-linux(-ng) flock
On Linux systems, there is a `flock' command (from `util-linux' or `util-linux-ng') that can be used to run a command inside a file lock/unlock block.
function run_lock_flock { LOCK=$1 shift touch "$LOCK" flock "$LOCK" "$@" }
portable way with perl
On other Unix systems, a portable way could be to use perl to mimic the util-linux(-ng) command shown above:
function run_lock_perl { LOCK=$1 shift perl -e ' use Fcntl":flock"; $l=shift; open(L,">>",$l)||die"Error open: $!\n";flock(L,LOCK_EX)||die"Error lock: $!\n"; system(@ARGV);$?==-1&&die"Error executing command!"; flock(L,LOCK_UN);close(L); exit($?>>8) ' "$LOCK" "$@" }
autodetect flock
Finally, a main `run_lock' function to autodetect which type of flock to use, and run the given command with the given lock file.
function run_lock { type -p flock if [ $? -eq 0 ]; then run_lock_flock "$@" else run_lock_perl "$@" fi } run_lock mylock.lck /usr/bin/foo -c bar -l baz