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?

tuk
  • 5,941
  • 14
  • 79
  • 162

1 Answers1

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.

Community
  • 1
  • 1
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 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`? – Paul Hodges Nov 05 '18 at 17:05
  • @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? – tuk Nov 26 '18 at 12:13
  • Depends on how it's implemented. Can't say I know. Worth some research if it matters. – Paul Hodges Nov 26 '18 at 14:01
  • 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. – KamilCuk Nov 26 '18 at 14:01
  • However, according to this [this thread](https://stackoverflow.com/questions/2636127/flock-locking-order) 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](https://elixir.bootlin.com/linux/v4.19.4/source/fs/locks.c#L682). So I guess you can (currently) count that they will wake up in the same order on linux kernel. – KamilCuk Nov 26 '18 at 14:03