Jonathan has asked for the wisdom of the Perl Monks concerning the following question:

I want to be able to pull in the output from the log of a process I've set off earlier in the script.
So really I want a tail -f of its log file.


Any monk out there with an elegant solution?

Replies are listed 'Best First'.
Re: tee -f?
by Anonymous Monk on Jun 20, 2000 at 20:17 UTC
    From perlfaq5...
    seek(GWFILE, 0, 1);
    This clears the end-of-file condition on the handle, so that the next <GWFILE> makes Perl try again to read something.
    If that doesn't work (it relies on features of your stdio implementation), then you need something more like this:
    for (;;) { for ($curpos = tell(GWFILE); <GWFILE>; $curpos = tell(GWFILE +)) { # search for some stuff and put it into files } # sleep for a while seek(GWFILE, $curpos, 0); # seek to where we had been }
    If this still doesn't work, look into the POSIX module. POSIX defines the clearerr() method, which can remove the end of file condition on a filehandle. The method: read until end of file, clearerr(), read some more. Lather, rinse, repeat.

    There's also a File::Tail module from CPAN.

Re: tee -f?
by lhoward (Vicar) on Jun 20, 2000 at 20:20 UTC
    I've used something like this before:
    use IO::File; use strict; my $tail = new IO::File; $tail->open("<./log.dat"); while(1){ my @lines=$tail->getlines(); if(0==scalar(@lines)){ # wait 1 second before trying again... # to keep from hogging CPU cycles sleep 1; }else{ my $line; foreach $line(@lines){ chomp $line; print " \"$line\"\n"; } } }
    I've originally wrote this code w/ a select/can_read but it ended up hogging the CPU so I put in the 1 second sleep.

    A few problems with this code:

    1. Up to a 1 second delay between data being flushed to the log and the program detecting it
    2. Can't detect EOF, keeps waiting for more data even after the writing program has closed the logfile. Of course, tail -f has this same problem.
    The program writing to the logfile needs to be flushing its output or you may get irregular results (i.e. sometimes partial lines, etc....).
      Thanks, this looks like it will do the job nicely for what I need to do.
Re: tee -f?
by chromatic (Archbishop) on Jun 20, 2000 at 23:14 UTC
    The ever-wise Uri Guttman has finally uploaded File::ReadBackwards to the CPAN.

    From its description, it looks like what you want.

Re: tee -f?
by nuance (Hermit) on Jun 20, 2000 at 19:11 UTC

    how about:

    @log = qx{tail -f $mylogfile};

    Updated: leave out the -f (see reply below). I'm sorry I can't do better than that I don't have accces to the man command on my linux box (I'm in work).

    Nuance

      Surely that line would not finish until the tail had reached EOF and tail -f doesn't - it just waits for more input
      Sorry Nuance I don't think that would work either, tail on its own will only return n number of records, its the stream itself I want to attach to.

      Thanks anyway