A very basic tail -f implementation

From: James F.Hranicky [mailto:jfh@cise.ufl.edu]

If you want to tail beginning at an arbitrary position in the file,
that will work, but many will probably want to specify the # of lines
from the end.

I agree. I don’t think the *nix tail command even allows you to tail from a
specific byte position, though I could be wrong. I can’t see much use for
that myself.

You could seek to the end, then seek backwards in chunks, read in each
chunk, then count backwards through the chunk counting newlines and
keeping track of filepos, and once you hit the # lines you
want, seek to
that position and then read from there. This would cut down on the #
of seeks and reads in my method above, probably resulting in much
better performance.

I proposed this in my last solution, though it doesn’t grab a block of data
first. I know the source for tail does this, but if we’re counting char by
char anyway, how does first grabbing a 4k block (or whatever) help?

max default is 10

def get_lines(max)

  @fh.seek(0,IO::SEEK_END)
  newline_count = 0
  while newline_count < max 

     begin
        @fh.pos -= 2
     rescue Errno::EINVAL
        break
     end

     break if @fh.eof?

     if @fh.getc.chr == "\n"
        newline_count += 1
     end
  end

  @fh.readlines

end

Regards,

Dan

···

-----Original Message-----

Say you wanted to tail 100,000 lines before your tail -f . Given 80 chars
per line, thats 8,000,000 seeks and reads, vs 2000 seeks and reads for
reading in 4k chunks. The comparison for c == “\n” gets done the same

of time in each version, so unless reading in 4k chunks with one

seek/read vs reading in the same with 4000 seeks/reads is slower
(low memory, perhaps), I’d think the chunked version should be much
faster.

Or am I off base here?

···

On Fri, 2 Aug 2002 23:55:42 +0900 “Berger, Daniel” djberge@qwest.com wrote:

I proposed this in my last solution, though it doesn’t grab a block of data
first. I know the source for tail does this, but if we’re counting char by
char anyway, how does first grabbing a 4k block (or whatever) help?


Jim Hranicky, Senior SysAdmin UF/CISE Department |
E314D CSE Building Phone (352) 392-1499 |
jfh@cise.ufl.edu http://www.cise.ufl.edu/~jfh |


“Given a choice between a complex, difficult-to-understand, disconcerting
explanation and a simplistic, comforting one, many prefer simplistic
comfort if it’s remotely plausible, especially if it involves blaming
someone else for their problems.”
– Bob Lewis, Infoworld