开发者

Linux: For "tail -f filename", does the follow read lines only after a \n?

开发者 https://www.devze.com 2023-02-25 05:10 出处:网络
Initial File: line 1 line 2 line 3 File after append 1: line 1开发者_如何学Go line 2 line 3 lin File after append 2:
Initial File:
line 1
line 2
line 3

File after append 1:
line 1开发者_如何学Go
line 2
line 3
lin

File after append 2:
line 1
line 2
line 3
line 4

If I do a "tail -f filename", and then the file gets updated as above,

Does tail follow on with updates of half a line, or does it only return atomic lines?

i.e.

Am I guaranteed to see/not-see "lin" after append 1? If there is no \n after "line 4", will I see it?

In particular, I'm interested in whether I can read atomic lines. I'm running a log monitoring application, and I only want to parse complete lines. The log files might be updated to half a line, and if tail doesn't guarantee atomic lines, I will have to guard against that (i.e. read char by char and then identify a line when I see the \n).


On my mac (9.8.0 Darwin Kernel Version 9.8.0) the built-in tail shows characters appended to the file. Here is a small test:

import sys, time

def write(fname):
  fd = open(fname, 'wb')
  try:
    while True:
      for i in range(0, 5): 
        fd.write('a')
        fd.flush()
        print >>sys.stderr, "Wrote a char"
        time.sleep(2)
      fd.write('\n')
      fd.flush()
      print >>sys.stderr, "Wrote newline"
      time.sleep(2)
  finally:
    fd.close()

if __name__ == '__main__':
  write(sys.argv[1])

Run: python test.py test.txt and then tail -f test.txt. It shows appearing a-s.


Well according to the man page:

-f, --follow[={name|descriptor}]
          output appended data as the file grows; -f, --follow, and --follow=descriptor are equivalent

so that implies you'll see each character as it's appended, not just on new line. However, I imagine tail employs some kind of flushing strategy, so what you see may depend on how fast the file is being updated. I can only suggest you experiment a bit.


The thing is that there is buffering.

Tail will probably do buffering, but the source may well be linebuffering. If the source is under your control, try to disable output buffering and see how that goes

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号