ShaZe has asked for the wisdom of the Perl Monks concerning the following question:
Hello Perl Monks!
I have a question related to the read/ write operations happening on a server. I currently have a basic script that log each time a name and a time in a file. If the time is lower than the ones in the list, they are moved higher in the list. I then save the list and close the file.
The code is functional and there isn't any error seen when the function is tested alone. However in a real case scenario, the file often appear incomplete. The file will end at a partially written name or time.
Do you have any idea what could be wrong?
Here's the code I have :
Let me know what you think#!/usr/bin/perl -- ################################################ use strict; use warnings; use Fcntl qw(:flock :seek); print "Content-type: text/html\n\n"; UpdateInfo("testname1", "240"); sub UpdateInfo { my $name = $_[0]; my $time = $_[1]; my $file = "file.dat"; my $lock = "file.sem"; open SEM, ">$lock" or die "Can't write-open $lock: $!"; flock SEM, LOCK_EX; my $output; my @lines; if(-e $file) { open(LEVELINFO, $file); while (defined(my $line = <LEVELINFO>)) { chomp $line; push (@lines, $line); } close(LEVELINFO); $lines[0] = "header\t0\t0\n"; my $currentEntry = 0; for (my $i = 1; $i < @lines; $i++) { (my $currName, my $currTime) = split(/\t/, $lines[$i]); if($currName eq $name) { if($time < $currTime) { $currentEntry = $i; } } $lines[$i] = $lines[$i] . "\n"; } if($currentEntry != 0) {splice @lines, $currentEntry, 1;} my $boolAdded = 0; for (my $i = 1; $i < @lines; $i++) { (my $currName, my $currTime) = split(/\t/, $lines[$i]); if($boolAdded == 0 and $time < $currTime) { splice @lines, $i, 0, "$name\t$time\n"; $boolAdded = 1; } } if(@lines < 11 and $boolAdded == 0) { push @lines, "$name\t$ti +me\n"; } open(LEVELINFO, ">$file"); for my $i (0..$#lines) { print LEVELINFO $lines[$i]; if($i > 0) { $output = $output . "$lines[$i]"; } } close(LEVELINFO); } else { push @lines, "header\t0\t0\n"; push @lines, "$name\t$time\n"; open(LEVELINFO, ">$file"); for my $i (0..$#lines) { print LEVELINFO $lines[$i];} close(LEVELINFO); } close(SEM); unlink($lock); return $output; }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Read / Write Server
by roboticus (Chancellor) on Mar 04, 2015 at 21:46 UTC | |
by ShaZe (Novice) on Mar 04, 2015 at 22:11 UTC | |
|
Re: Read / Write Server
by Laurent_R (Canon) on Mar 04, 2015 at 22:54 UTC | |
|
Re: Read / Write Server
by cheako (Beadle) on Mar 05, 2015 at 05:12 UTC | |
|
Re: Read / Write Server
by ShaZe (Novice) on Mar 04, 2015 at 23:16 UTC |