Hello Wise Monks. I've been having trouble with the following code especially when several people run my script at the same time. What happens is that sometimes, when I view the file named "counter", it reflects a number lower than what it was the previous day, perhaps because the file was deleted somehow. But I don't see any way the file would be deleted. Please help?
sub get_lock
{
open(SEM, ">$semaphore_file") || die "Cannot create semaphore $semap
+hore_file: $!";
flock(SEM, LOCK_EX) || die "Lock failed: $!";
}
sub release_lock
{
close(SEM);
}
sub readdata
{
my @filedata; @filedata=();
open(MFILE, ">>$completeadd") || die "file open2 failed at $complete
+add: $!\n";
close(MFILE);
open(MFILE, "$completeadd") || die "file open81 failed: $!\n";
@filedata=<MFILE>;
chomp @filedata;
close(MFILE);
return(@filedata);
}
sub writedata
{
my @filedata; @filedata=();
@filedata=@_;
open(MFILE, ">$completeadd") || die "file open3 failed: $!\n";
foreach(@filedata)
{
print MFILE "$_\n";
}
close(MFILE);
}
$completeadd = "counter";
$semaphore_file = "counterLOCK";
get_lock();
if (-e $completeadd)
{
open(MFILE, "$completeadd") || die "file open4 failed: $!\n";
@filedata1=<MFILE>;
chomp @filedata1;
close(MFILE);
}
else
{
@filedata1=readdata();
}
$hitcount=$filedata1[0];
if ($hitcount)
{
$hitcount=$hitcount + 1;
}
else
{
$hitcount = 1;
}
$filedata1[0]=$hitcount;
writedata(@filedata1);
release_lock();
close(CNTLCK);
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.