Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re:What is the best way to lock a counter file?

by Ovid (Cardinal)
on Jun 25, 2000 at 10:37 UTC ( [id://19741]=note: print w/replies, xml ) Need Help??


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!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://19741]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (9)
As of 2024-04-23 17:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found