Tim Woodall (HE12025-10-23):
> I'm converting a (bash) script from using lockfiles to using flock but I'm
> getting a strange effect that I don't understand.
> 
> FWIW, the old script used mkdir where I call flock and rmdir where I close
> the fd. (I also used a trap to avoid stale lockfiles.
> 
> queue_cmd()
> {
>   (
>     local lck=/etc/network/lock/${1##*/}
>     exec {FDQUEUE}>$lck.queue
>     flock -n ${FDQUEUE} || exit 0
> 
>     exec {FDLOCK}>$lck.lock
>     while ! flock -n ${FDLOCK}; do
>         echo "Waiting for $lck.lock to be unlocked"
>         sleep 10
>     done
>     exec {FDQUEUE}>&-
> 
>     echo running: $@
>     "$@"
>     echo finished running: $@
> 
>     exec {FDLOCK}>&-
>     echo release lock: $@
>   ) &
> }
> 
> The job of this function is to run a script, or queue it if its already
> running but only have one run queued. I want my firewall to run every time
> the network changes but there's no benefit to running it twice if the first
> run also picks up the network changes from the second change.
> 
> But now it doesn't seem to unlock after "finished running". I didn't think
> the explicit unlock was required anyway but with or without it's not doing
> what I expect. If I use flock -u then it does unlock.
> 
> This is what happens with the code exactly as written (or without the
> explicit closing of FDLOCK)

It should not be, and it would be interesting to determine how. What you
need to do is use lsof or equivalent to determine which process still
has your lock file open.

But what you did here was translate word-for-word your dot-locking
mechanism into flock: you gained nothing, and it is awkward: you use the
-n option that means “do not wait for the lock” in a loop that says
“waiting for the lock”, it is absurd.

To reap the benefits from migration to flock, you need to use the first
syntax shown in the man page.

Regards,

-- 
  Nicolas George

Reply via email to