Skip to content

Instantly share code, notes, and snippets.

@riywo
Last active December 12, 2015 07:19
Show Gist options
  • Save riywo/4736159 to your computer and use it in GitHub Desktop.
Save riywo/4736159 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use Fcntl qw/:DEFAULT :flock/;
use File::stat;
sub _parse_stats_file {
my ($self) = @_;
my $stats_fh = $self->_stats_fh();
my $results = +{};
while (<$stats_fh>) {
...
}
close $stats_fh;
return $results;
}
sub _stats_file {
my ($self) = @_;
return "/tmp/stats"
}
sub _stats_fh {
my ($self) = @_;
sysopen my $fh, $self->_stats_file(), O_RDWR|O_CREAT or die $!;
flock $fh, LOCK_SH or die $!;
my $size = stat($self->_stats_file())->size;
my $mtime = stat($self->_stats_file())->mtime;
if ($size == 0 or $mtime < time - $self->{expire_sec}) {
flock $fh, LOCK_EX or die $!;
$self->_write_stats_file($fh);
}
return $fh;
}
sub _write_stats_file {
my ($self, $fh) = @_;
seek($fh, 0, 0);
...
truncate($fh, tell($fh));
seek($fh, 0, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment