Reputation: 6872
I have a bash script runner.sh
which invokes another script.sh
. script.sh
is invoked only from runner.sh
. I can have only one instance of script.sh
executing at a time. If multiple invocations of runner.sh
is made then runner.sh
should make all the caller's wait if script.sh
is already running. Once script.sh
is completed then it will allow one of the waiting callers to execute script.sh
.
Can someone suggest some ways of achieving this?
Upvotes: 1
Views: 901
Reputation: 141383
From man flock:
[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :
This is useful boilerplate code for shell scripts. Put it at the top of the shell script you want to lock and it'll automatically lock itself on the first run. If the env var $FLOCKER is not set to the shell script that is being run, then execute flock and grab an exclusive non-blocking lock (using the script itself as the lock file) before re-execing itself with the right arguments. It also sets the FLOCKER env var to the right value so it doesn't run again.
Put this on top of ./script.sh
(or on top of runner.sh
) and your're good to go.
Upvotes: 3