Fixed two bugs in tail.c.
authorviric@llimona
Mon, 21 Jan 2008 23:57:06 +0100
changeset 187 85d52acbab26
parent 186 fa662c2736f7
child 188 64058e15c0dd
Fixed two bugs in tail.c.
tail.c
--- a/tail.c	Thu Jan 17 23:38:42 2008 +0100
+++ b/tail.c	Mon Jan 21 23:57:06 2008 +0100
@@ -50,6 +50,8 @@
     int move_offset;
     int i;
 
+    last_lseek = lseek(fd, 0, SEEK_END);
+
     do
     {
         int next_read;
@@ -62,7 +64,7 @@
 
         /* last_lseek will be -1 at the beginning of the file,
          * if we wanted to go farer than it. */
-        last_lseek = lseek(fd, -BSIZE, SEEK_END);
+        last_lseek = lseek(fd, -BSIZE, SEEK_CUR);
 
         if (last_lseek == -1)
             last_lseek = lseek(fd, 0, SEEK_SET);
@@ -85,6 +87,9 @@
                     break;
             }
         }
+        
+        /* Go back the read bytes */
+        last_lseek = lseek(fd, -last_read, SEEK_CUR);
     } while(lines_found < lines);
 
     /* Calculate the position */
@@ -92,6 +97,14 @@
     lseek(fd, move_offset, SEEK_CUR);
 }
 
+static void set_non_blocking(int fd)
+{
+    long arg;
+
+    arg = O_RDONLY | O_NONBLOCK;
+    fcntl(fd, F_SETFL, arg);
+}
+
 int tail_file(const char *fname)
 {
     int fd;
@@ -109,6 +122,12 @@
 
     seek_at_last_lines(fd, 10);
 
+    /* we don't want the next read calls to block. */
+    set_non_blocking(fd);
+
+    /* We don't want line-buffered stdoutput */
+    setvbuf(stdout, 0, _IONBF, 0);
+
     do
     {
         char buf[BSIZE];
@@ -149,7 +168,7 @@
         res = read(fd, buf, BSIZE);
         if (res == -1)
         {
-            if (errno == EINTR)
+            if (errno == EINTR || errno == EAGAIN)
             {
                 res = 1; /* Hack for the while condition */
                 continue;