Skip to content

Instantly share code, notes, and snippets.

@lestrrat
Created January 25, 2012 01:31
Show Gist options
  • Save lestrrat/1674004 to your computer and use it in GitHub Desktop.
Save lestrrat/1674004 to your computer and use it in GitHub Desktop.
tail -f with AnyEvent (is this correct?)
use strict;
use AnyEvent;
use Fcntl qw(SEEK_SET);
use Linux::Inotify2;
main(@ARGV);
sub main {
my $file = shift or die "no file specified";
# XXX Hmmm, kinda odd. Maybe it's better to read once from the end and
# set the position? hmm
my $offset = -s $file;
my $inotify = Linux::Inotify2->new or die;
my $io = AE::io $inotify->fileno, 0, sub { $inotify->poll };
my $cv = AE::cv { undef $io };
my $quit = sub {
$cv->send;
};
AE::signal TERM => $quit;
AE::signal HUP => $quit;
AE::signal INT => $quit;
my %counter;
my $buf;
open my $fh, '<', $file or die "could not open file $file: $!";
$inotify->watch( $file, IN_MODIFY, sub {
sysseek $fh, $offset, SEEK_SET;
my $n_read = sysread $fh, $buf, 8192, length($buf);
if ( $n_read > 0 ) {
$offset += $n_read;
# got something to read. (in this case I'd like to process by line,
# so I'm going through all this to detect new lines)
my $index = index $buf, "\n";
while ($index >= 0) {
my $line = substr $buf, 0, $index + 1, '';
print "LINE: $line";
$index = index $buf, "\n";
}
}
} );
$cv->recv;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment