in reply to What is the best way to lock a counter file?

It's difficult to tell what the error is if you don't supply us with the actual error message. If the file is on a network file system, flock is unlikely to work. Further, flock is a polite way of requesting that others leave the file alone. It does not actually stop the file from being used by someone else unless they check to see if it's locked. (That's probably not relevant to your question, but I thought I would mention it).

Here's a somewhat cleaner version of your code (straight from the Perl Cookbook):

use Fcntl qw(:DEFAULT :flock); sysopen(FH, $file_banner, O_RDWR|O_CREAT) or die "Can't open $file_ban +ner: $!\n"; flock(FH, LOCK_EX) or die "Can't write-lock $file_ +banner: $!\n"; $num = <FH> || 0; # do not use 'or' here seek(FH, 0, 0) or die "Can't rewind $file_bann +er: $!\n"; truncate(FH,0) or die "Can't truncate $file_ba +nner: $!\n"; print FH $num+1, "\n" or die "Can't write to $file_ba +nner: $!\n"; close(FH) or die "Can't close $file_banne +r: $!\n";
Note that the above code will create the file for you if it does not exist. Thus, the if/else structure is eliminated.

Hope this helps.

Cheers!