Log Observer Implementation

I am wondering how you can implement a program similar to tail -fin C / C ++, a program that tracks and processes new lines added to a log file?

+3
source share
4 answers

You can use fseek () to clear the eof condition from the stream. Essentially, read to the end of the file, sleep for a while, fseek () (without changing your position) to clear eof, reading to the end of the file again. rinse, rinse, repeat. man fseek (3) for details.

This is how it looks in perl. perl seek () is essentially a wrapper for fseek (3), so the logic is the same:

wembley 0 /home/jj33/swap >#> cat p
my $f = shift;
open(I, "<$f") || die "Couldn't open $f: $!\n";

while (1) {
  seek(I, 0, 1);
  while (defined(my $l = <I>)) {
    print "Got: $l";
  }
  print "Hit EOF, sleeping\n";
  sleep(10);
}
wembley 0 /home/jj33/swap >#> cat tfile
This is
some
text
in
a file
wembley 0 /home/jj33/swap >#> perl p tfile
Got: This is
Got: some
Got: text
Got: in
Got: a file
Hit EOF, sleeping

Then in another session:

wembley 0 /home/jj33/swap > echo "another line of text" >> tfile

And back to the original output of the program:

Hit EOF, sleeping
Got: another line of text
Hit EOF, sleeping
+5
source

Look here

, , , .

, ++ iostream , 10-20 , .

0

The tail program is open source, so you can link to it. I also wondered and looked at the code some time ago, thinking that it would be quite simple, but I was surprised how complicated it was. There are many errors that need to be taken into account.

0
source

Source: https://habr.com/ru/post/1696493/


All Articles