What you don't seem to realize is that
flock blocks. That is, if you call it at a point when it cannot get a lock for normal reasons (ie the file is already locked by someone else), it will wait indefinitely. Your program will be stuck at the
flock and won't continue executing until it has obtained the lock. When it continues, you will
always have a lock.
Except if something very strange happened, in which case it is good to
die noisily at that point because that is a clear indicator that something is very wrong with the system. You're not likely to be able to function properly aftewards anyway.
You
can make
flock nonblocking by adding a flag to the function call. However, this is only useful in specific circumstances. You shouldn't try it unless you understand why it is necessary.
And a sidenote: please
use Fcntl; and write your
flock calls using constants.
flock(FILE, LOCK_SH); is much clearer than
flock(FILE, 1);. Also, you may want to look up the difference between
LOCK_SH and
LOCK_EX; it's important to know of the existance of both and to understand when to use which.