in reply to Re: counter
in thread On server, counter file is read-only
This is a Unix environment. That means, multitasking. It's not a PC, two things can actually happen at the same time! Hence, you need to use critical sections in your code - and lock the file. Here's a suggestion of how to tackle the problem:
But this is just shown for educational purposes. Using counters on webpages is so mid-nineties, people have done it before, and there are ready to use programs and modules out there. And I bet Randal has a column about it....use strict; use warnings 'all'; use Fcntl qw /:DEFAULT :flock :seek/; my $counter_file = "/tmp/counter"; sysopen my $fh => $counter_file, O_RDWR | O_CREAT, 0644 or die "Failed to open $counter_file: $!\n"; flock $fh => LOCK_EX or die "Failed to flock $counter_file: $!\n" +; chomp (my $counter = <$fh> || 0); $counter ++; seek $fh => 0, SEEK_SET; print $fh "$counter\n" or die "Failed to write to $counter_file: $! +\n"; truncate $fh => tell $fh or die "Failed to truncate $counter_file: $! +\n"; close $fh or die "Failed to close $counter_file: $!\n" +; ... Do whatever you want with $counter here ....
Abigail
|
|---|