Gerard has asked for the wisdom of the Perl Monks concerning the following question:
Which I gleamed from another post here at the monastery. When running this a lot of times in quick succession with files being created and removed in between (but not at the same time), about one time in 10 this will break, not returning any value (when there are definitely files in the directory). Perplexed I have changed the line my $oldest_age = 0; to my $oldest_age = -1; Thinking that possibly the $age could be = 0 when there is only one file....This seems to have helped a lot, reducing the number of "breaks" down to about 1 in 100, but there are still multiple files in the directory. (In my tests, 5 and 8).sub get_oldest_file { my $path = shift; # name of directory to search opendir( D, $path ) or return "Unable to read directory $path\n"; my $oldest_age = 0; my $oldest_name = ''; for ( readdir( D )) { next unless ( -f "$path/$_"); my $age = ( -M _ ); # note the "_" : uses stat data loaded by +"-f" above if ( $age > $oldest_age ) { $oldest_name = $_; $oldest_age = $age; } } closedir D; return $oldest_name; }
This now runs most of the time, but not all the time... It dies when trying to check the file size, as $filename doesn't contain anything.sub GetMessage { my $filename; my $timeout = $q->param('Timeout'); # default timeout period is 10 seconds if ($timeout eq ""){ $timeout = 10; } $branch = $q->param('Branch'); my $dir = $baseDir . "\\" . $branch . "\\"; # first check to see if the directory exists if(! -e $dir){ &error("Requested branch at " . $dir . " does not exist"); } chdir($dir) ; eval { local $SIG{ALRM} = sub { die "alarm\n" }; alarm $timeout; # This process may take a while. If it does not complete withi +n $timeout seconds # it will be stopped. $filename=get_oldest_file("."); alarm 0; }; if ($@ eq "alarm\n") { # TIMED OUT - Was unable to calculate the oldest file in the g +iven # timeout period. Return not found print $q->header('text/html','404 Not Found - operation timed +out'); exit (0); } else { # Found the oldest file ok. Continue processing. my $size; $size = -s $filename || error("Unable to check file size " . $ +dir . $filename . " : " . $!); my $messageID = $filename; print $q->header(-Type=>'application/octet-stream', -Message_ID=>$messageID, -Content_Length=>$size); open(MSG,"< $filename") || error("Unable to open file " . $dir + . $filename . " for read: " . $!); binmode MSG; while(<MSG>) { print $_; } close MSG; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
•Re: Oldest file using -M
by merlyn (Sage) on Apr 27, 2004 at 05:23 UTC | |
by Gerard (Pilgrim) on Apr 27, 2004 at 20:40 UTC | |
|
Re: Oldest file using -M
by ehdonhon (Curate) on Apr 27, 2004 at 14:18 UTC | |
by merlyn (Sage) on Apr 27, 2004 at 14:22 UTC | |
by Gerard (Pilgrim) on Apr 27, 2004 at 23:37 UTC |