[Gambas-user] file read and growing logfile
Benoît Minisini
gambas at ...1...
Mon Mar 23 15:49:22 CET 2009
> Ron schreef:
> > How to watch new data that's added to a logfile?
> >
> > I want to make an apache log monitor, so I thought I could do that with
> > FILE READ WATCH, but thats not suited it seems, that one only seems keep
> > generating File_Read events continuous.
> >
> > In short:
> > I want to open a file readonly.
> > Then seek to end of file (or just before it)
> > Then only get file_read events when new lines/data are added (by
> > apache)..
> >
> > Anyone has any ideas?
>
> In response to my own question I have tested with this:
>
> It creates a file and reads it, event File_Read() keeps getting raised,
> even after end of file.
>
> ' Gambas module file
> PRIVATE hFile AS File
> PRIVATE hFile2 AS File
>
> PUBLIC SUB Main()
>
> ' create test file
> hFile = OPEN "/tmp/file" FOR WRITE CREATE
> PRINT #hFile, "0123456789";
> CLOSE #hFile
>
> ' watch it
> hFile2 = OPEN "/tmp/file" FOR READ WATCH
>
> END
>
> PUBLIC SUB File_Read()
>
> DIM iByte AS Byte
>
> READ #hFile2, iByte
> PRINT " "; iByte;
>
> END
>
> It prints:
> 48 49 50 51 52 53 54 55 56 57
>
> And then gives error "End of File"
>
> This is not what I expected, shouldn't it stop before end of file?
>
> Gambas 2.12, gb.qt
>
> Regards,
> Ron_2nd.
>
It should, but alas this is not the way Linux works as explained in the man
page of the select() system call.
A file descriptor is ready to read if the read() system call won't block. And
this is the case even if the end of file is reached, as then read() returns an
error (and so does not block!).
If you actually want to do what the "tail" command (watching a file and print
its contents), you should do that:
- Get the file size every second.
- If the file size has changed since the last time, read the file from its
last position until the end of the file.
Regards,
--
Benoît
More information about the User
mailing list