in reply to Concurrent file access with flock()

The error that you have is very often seen as a result of a race condition when your open mode is +> or if locking did not work. It should not happen if your mode is +< and you check for locking (which you do).

Therefore it is odd that you are seeing the problem.

But the fact that this code is clearly inline in the top of a script is suspicious. I would strongly suggest that you look through all of your scripts which access counter.txt and see if any of them has omitted locking or has the wrong open mode. I would further suggest that, rather than write the same locking code in each script, you write a function in a library and then call that function from everywhere. This reduces code duplication, and keeps you from having to look for problems like this in lots of places to make sure that you caught the last place that the bug is to be found.