[Tutor] tail -f

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Tue, 26 Mar 2002 19:57:34 -0800 (PST)


On Tue, 26 Mar 2002, dman wrote:

> source for tail, but nothing unusual jumped out at me and said "this
> is how it does that!".  I tried to simply continue reading from the
> file, but that only chewed up the CPU and didn't yield any output when
> I echoed new data into the file.
>

> Does anyone here know how to follow a file efficiently and correctly?



GNU tail actually does something like busy waiting/polling, at least
according to the comments in it's code.

/***/
* Tail NFILES files forever, or until killed.
   The pertinent information for each file is stored in an entry of F.
   Loop over each of them, doing an fstat to see if they have changed
   size,
   and an occasional open/fstat to see if any dev/ino pair has changed.
   If none of them have changed size in one iteration, sleep for a
   while and try again. */

static void
tail_forever (struct File_spec *f, int nfiles)
{
  int last;
  int writer_is_dead = 0;

  last = nfiles - 1;

  while (1)
    {
    [ some code cut ]


/* If none of the files changed size, sleep.  */
      if (!any_changed)
        {
          if (writer_is_dead)
            break;
          sleep (sleep_interval);
/***/


So basically, they open the file, and just stare at it's size, forever (or
until the user gets tired).  Whenever the file size changes, it just
prints the remainder out to screen.  They do something like a time.sleep()
to make the busy waiting look less bad.  *grin* By default, they poll
every 1 second:

/***/
static unsigned int sleep_interval = 1;
/***/



Good luck to you!