# $Id: Log.pm,v 1.1 2005/02/05 21:59:47 jfontain Exp $

# Sample Perl asynchronous module to monitor a log file, using threads.
package Log;

use threads;
use Thread::Queue;
use strict;
use warnings;

BEGIN {
    our $VERSION = qw($Revision: 1.1 $)[1];
}

### unsuccessful try at reaping tail subprocesses on exit:
#$SIG{CHLD} = 'IGNORE';
$SIG{'CHLD'} = 'reaper';
sub reaper() {
    while (wait() != -1) {print("w\n");}
}


our %data;
our @data;

$data{updates} = 0;
$data{columns}[0] = {label => '', type => 'ascii', message => ''};
$data{columns}[1] = {label => 'data', type => 'dictionary', message => 'value'};
$data{pollTimes} = [-10];
$data{views} = [{indices => [1], sort => {1 => 'increasing'}}];
$data{persistent} = 1;
$data{switches} = {'-f' => 1}; ### implement: log file name option
$data[0][0] = '';

our $queue = Thread::Queue->new();

sub initialize(%) {
    open(LOG, "tail -F /var/log/messages 2>&1 |");
    threads->new(\&work);
}

sub work() {
    while (my $line = readline(LOG)) {
        chop($line);
        $queue->enqueue($line);
        yield('updated');
    }
}

sub updated() {
    $data[0][1] = $queue->dequeue();
    $data{updates}++;
}

1;
