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?
1 Answer 1
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.
5 Comments
-n?-n will the caller wait in the order in which they tried invoke the locked command ? or the order can be random?The documentation doesn't require this but * it seems like the reasonable thing to do. It's still present in current kernel. So I guess you can (currently) count that they will wake up in the same order on linux kernel.