Search code examples
cunixlseek

Alternative to lseek to tail a file (Posix)


I had to implement a version of tail (posix system call). I did it using lseek and pread. (I reach the end of my file then I search for the right offset position, and then read from this position with pread, and writes to stdout till the end of the file). But now, I have to implement another version of tail without lseek. The question is the following :

"Previous version does not work if the file does not support calls to lseek. Cite cases where this happens. Propose a solution (which you will not implement) to remedy this problem."

I don't understand how we can do without lseek...

If you have an idea, I'll be very grateful :)

Thank you very much !


Solution

  • Cite cases where this happens.

    For that, we check the man page to see what errors lseek can return.

    EBADF fd is not an open file descriptor.

    Usage error. Not relevant.

    EINVAL whence is not valid. Or: the resulting file offset would be negative, or beyond the end of a seekable device.

    Usage error. Not relevant.

    EOVERFLOW The resulting file offset cannot be represented in an off_t.

    Very large files. Relevant.

    ESPIPE fd is associated with a pipe, socket, or FIFO.

    Relevant.

    ENXIO whence is SEEK_DATA or SEEK_HOLE, and the current file offset is beyond the end of the file.

    Usage error. Not relevant.

    File shrunk. Relevant.


    Propose a solution (which you will not implement) to remedy this problem.

    • EOVERFLOW

      This can be solved by switching to lseek64. This will allow you to work with files up to 8 exbibyte in size. (That's 8,589,934,592 GiB.)

    • ESPIPE

      Pipes, sockets and fifos actually much easier to tail than plain files. When reading from one of those, read will block waiting for more data instead of returning when you reach their end. There's no reason to adopt the complicate seeking algorithm used for plain files; one can simply call read in a loop.

    • ENXIO

      Tailing a file inherently presumes the only modification being made to the file being tailed is the appending of new lines. This error indicates some other kind of change was performed to the file. This is an error that can't be avoided.

      tail emits a warning (file truncated) and proceeds to tail from the new EOF.