#!/usr/bin/perl -w
use strict;
use Linux::Inotify2;
select((select(STDOUT), $| = 1)[0]);
my $notify = new Linux::Inotify2 or die "inotify fail";
sub unload {
open my $I, '+<', "sse/users" or die "can't open users file";
unlink "sse/users";
open my $O, '>', "sse/users~" or die "can't rewrite users file";
print $O grep { $_ ne "$ENV{REMOTE_ADDR}\n" } <$I>;
rename "sse/users~", "sse/users";
close $I; close $O;
}
END { unload() }
open my $F, '>>', "sse/users" or die "can't open users file";
print $F "$ENV{REMOTE_ADDR}\n";
close $F;
sub update {
open my $F, '<', "sse/data" or die "can't open watched file";
local $_ = join '', map { $_ =~ s/[\r\n]*//g; $_ } <$F>;
close $F;
print "data:$_\r\n\r\n";
}
print "Content-type: text/event-stream\r\n\r\n";
$notify->watch("sse/data", IN_CLOSE_WRITE, \&update);
update;
# parent
if (my $pid = fork) {
$SIG{TERM} = sub {
kill 'TERM', $pid;
wait;
exit;
};
$notify->read while 1;
}
# child
for (;;) {
sleep 45;
print ":\r\n\r\n";
}