in reply to flock issue

When I was first getting the hang of flock I found it very useful to have a sample script like the above which at each stage printed what stage it was at, waited for input, and then continued. Running this in multiple terminals allowed me to walk through various possible race conditions and see what exactly was happening.

I recommend trying that.

An incidental note that you are completely missing above, if you will be writing a shorter string than was there before it is important that you truncate the file.

Incidentally for working code that puts all of this together you should try Simple Locking. I should note that I generally prefer sentinel files as an approach. They allow you to use flocks to produce mutexes around logical units of actions, which may not be just limited to manipulations of a single file.