1

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?

asked Nov 5, 2018 at 16:43
0

1 Answer 1

3

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.

answered Nov 5, 2018 at 16:50
Sign up to request clarification or add additional context in comments.

5 Comments

Won't this fail rather than wait if it can't get a lock? To make instances wait rather than fail, wouldn't you just drop the -n?
@PaulHodges - If I drop -n will the caller wait in the order in which they tried invoke the locked command ? or the order can be random?
Depends on how it's implemented. Can't say I know. Worth some research if it matters.
The processes are scheduled by the scheduler. Whichever process gets the CPU time first after the flock has been released will get the lock and continue execution. In short: it's random. You would need to create smth like a "waitqueue" to get them to order themselve.
However, according to this this thread looks like they are woken up in the same order they were blocked. 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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.