in reply to Re: Writing to a New File
in thread Writing to a New File
Oh how many times have I seen this code crap out!
You have a race condition. flock the file while you're working on it. In order to maintain the lock, you won't be able to close and reopen the file, so you'll have to open the file using in read-write mode and use seek.
use Fcntl qw( LOCK_EX SEEK_SET ); my $flashcount_file = '/var/www/html/log/flashcount.txt'; open(my $flashcount, '+<', $flashcount_file) or die; flock($flashcount, LOCK_EX) or die; my $count = <$flashcount>; $count =~ s/^count=//; $count++; seek($flashcount, 0, SEEK_SET) or die; # Not needed in this case. truncate($flastcount, 0) or die; print $flashcount "count=$count\n";
Untested.
Note: The code assumes the file already exists.
Update: Added code.
|
|---|