in reply to What is the best way to lock a counter file?
Here's a somewhat cleaner version of your code (straight from the Perl Cookbook):
Note that the above code will create the file for you if it does not exist. Thus, the if/else structure is eliminated.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";
Hope this helps.
Cheers!
|
|---|