1 /* tail -- output the last part of file(s)
2 Copyright (C) 89, 90, 91, 95, 1996 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18 Original version by Paul Rubin <phr@ocf.berkeley.edu>.
19 Extensions by David MacKenzie <djm@gnu.ai.mit.edu>.
20 tail -f for multiple files by Ian Lance Taylor <ian@airs.com>.
22 Rewrote the option parser, removed locales support,
23 and generally busyboxed, Erik Andersen <andersen@lineo.com>
33 #include <sys/types.h>
34 #include <sys/types.h>
41 /* Disable assertions. Some systems have broken assert macros. */
45 static void error(int i, int errnum, char* fmt, ...)
49 va_start(arguments, fmt);
50 vfprintf(stderr, fmt, arguments);
51 fprintf(stderr, "\n%s\n", strerror( errnum));
57 #define XWRITE(fd, buffer, n_bytes) \
61 assert ((n_bytes) >= 0); \
62 if (n_bytes > 0 && fwrite ((buffer), 1, (n_bytes), stdout) == 0) \
63 error (EXIT_FAILURE, errno, "write error"); \
67 /* Number of items to tail. */
68 #define DEFAULT_N_LINES 10
70 /* Size of atomic reads. */
72 #define BUFSIZ (512 * 8)
75 /* If nonzero, interpret the numeric argument as the number of lines.
76 Otherwise, interpret it as the number of bytes. */
77 static int count_lines;
79 /* If nonzero, read from the end of one file until killed. */
82 /* If nonzero, read from the end of multiple files until killed. */
83 static int forever_multiple;
85 /* Array of file descriptors if forever_multiple is 1. */
86 static int *file_descs;
88 /* Array of file sizes if forever_multiple is 1. */
89 static off_t *file_sizes;
91 /* If nonzero, count from start of file instead of end. */
92 static int from_start;
94 /* If nonzero, print filename headers. */
95 static int print_headers;
97 /* When to print the filename banners. */
100 multiple_files, always, never
105 /* The name this program was run with. */
108 /* Nonzero if we have ever read standard input. */
109 static int have_read_stdin;
112 static const char tail_usage[] =
113 "tail [OPTION]... [FILE]...\n\
115 Print last 10 lines of each FILE to standard output.\n\
116 With more than one FILE, precede each with a header giving the file name.\n\
117 With no FILE, or when FILE is -, read standard input.\n\
119 -c=N[kbm] output the last N bytes\n\
120 -f output appended data as the file grows\n\
121 -n=N output the last N lines, instead of last 10\n\
122 -q never output headers giving file names\n\
123 -v always output headers giving file names\n\
124 --help display this help and exit\n\
126 If the first character of N (bytes or lines) is a `+', output begins with \n\
127 the Nth item from the start of each file, otherwise, print the last N items\n\
128 in the file. N bytes may be suffixed by k (x1024), b (x512), or m (1024^2).\n\n";
131 write_header (const char *filename, const char *comment)
133 static int first_file = 1;
135 printf ("%s==> %s%s%s <==\n", (first_file ? "" : "\n"), filename,
136 (comment ? ": " : ""),
137 (comment ? comment : ""));
141 /* Print the last N_LINES lines from the end of file FD.
142 Go backward through the file, reading `BUFSIZ' bytes at a time (except
143 probably the first), until we hit the start of the file or have
144 read NUMBER newlines.
145 POS starts out as the length of the file (the offset of the last
146 byte of the file + 1).
147 Return 0 if successful, 1 if an error occurred. */
150 file_lines (const char *filename, int fd, long int n_lines, off_t pos)
154 int i; /* Index into `buffer' for scanning. */
159 /* Set `bytes_read' to the size of the last, probably partial, buffer;
160 0 < `bytes_read' <= `BUFSIZ'. */
161 bytes_read = pos % BUFSIZ;
164 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
165 reads will be on block boundaries, which might increase efficiency. */
167 lseek (fd, pos, SEEK_SET);
168 bytes_read = fullRead (fd, buffer, bytes_read);
169 if (bytes_read == -1)
171 error (0, errno, "%s", filename);
175 /* Count the incomplete line on files that don't end with a newline. */
176 if (bytes_read && buffer[bytes_read - 1] != '\n')
181 /* Scan backward, counting the newlines in this bufferfull. */
182 for (i = bytes_read - 1; i >= 0; i--)
184 /* Have we counted the requested number of newlines yet? */
185 if (buffer[i] == '\n' && n_lines-- == 0)
187 /* If this newline wasn't the last character in the buffer,
188 print the text after it. */
189 if (i != bytes_read - 1)
190 XWRITE (STDOUT_FILENO, &buffer[i + 1], bytes_read - (i + 1));
194 /* Not enough newlines in that bufferfull. */
197 /* Not enough lines in the file; print the entire file. */
198 lseek (fd, (off_t) 0, SEEK_SET);
202 lseek (fd, pos, SEEK_SET);
204 while ((bytes_read = fullRead (fd, buffer, BUFSIZ)) > 0);
205 if (bytes_read == -1)
207 error (0, errno, "%s", filename);
213 /* Print the last N_LINES lines from the end of the standard input,
214 open for reading as pipe FD.
215 Buffer the text as a linked list of LBUFFERs, adding them as needed.
216 Return 0 if successful, 1 if an error occured. */
219 pipe_lines (const char *filename, int fd, long int n_lines)
225 struct linebuffer *next;
227 typedef struct linebuffer LBUFFER;
228 LBUFFER *first, *last, *tmp;
229 int i; /* Index into buffers. */
230 int total_lines = 0; /* Total number of newlines in all buffers. */
233 first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
234 first->nbytes = first->nlines = 0;
236 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
238 /* Input is always read into a fresh buffer. */
239 while ((tmp->nbytes = fullRead (fd, tmp->buffer, BUFSIZ)) > 0)
244 /* Count the number of newlines just read. */
245 for (i = 0; i < tmp->nbytes; i++)
246 if (tmp->buffer[i] == '\n')
248 total_lines += tmp->nlines;
250 /* If there is enough room in the last buffer read, just append the new
251 one to it. This is because when reading from a pipe, `nbytes' can
252 often be very small. */
253 if (tmp->nbytes + last->nbytes < BUFSIZ)
255 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
256 last->nbytes += tmp->nbytes;
257 last->nlines += tmp->nlines;
261 /* If there's not enough room, link the new buffer onto the end of
262 the list, then either free up the oldest buffer for the next
263 read if that would leave enough lines, or else malloc a new one.
264 Some compaction mechanism is possible but probably not
266 last = last->next = tmp;
267 if (total_lines - first->nlines > n_lines)
270 total_lines -= first->nlines;
274 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
277 if (tmp->nbytes == -1)
279 error (0, errno, "%s", filename);
287 /* This prevents a core dump when the pipe contains no newlines. */
291 /* Count the incomplete line on files that don't end with a newline. */
292 if (last->buffer[last->nbytes - 1] != '\n')
298 /* Run through the list, printing lines. First, skip over unneeded
300 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
301 total_lines -= tmp->nlines;
303 /* Find the correct beginning, then print the rest of the file. */
304 if (total_lines > n_lines)
308 /* Skip `total_lines' - `n_lines' newlines. We made sure that
309 `total_lines' - `n_lines' <= `tmp->nlines'. */
311 for (i = total_lines - n_lines; i; --i)
312 while (*cp++ != '\n')
314 i = cp - tmp->buffer;
318 XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
320 for (tmp = tmp->next; tmp; tmp = tmp->next)
321 XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
327 free ((char *) first);
333 /* Print the last N_BYTES characters from the end of pipe FD.
334 This is a stripped down version of pipe_lines.
335 Return 0 if successful, 1 if an error occurred. */
338 pipe_bytes (const char *filename, int fd, off_t n_bytes)
344 struct charbuffer *next;
346 typedef struct charbuffer CBUFFER;
347 CBUFFER *first, *last, *tmp;
348 int i; /* Index into buffers. */
349 int total_bytes = 0; /* Total characters in all buffers. */
352 first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
355 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
357 /* Input is always read into a fresh buffer. */
358 while ((tmp->nbytes = fullRead (fd, tmp->buffer, BUFSIZ)) > 0)
362 total_bytes += tmp->nbytes;
363 /* If there is enough room in the last buffer read, just append the new
364 one to it. This is because when reading from a pipe, `nbytes' can
365 often be very small. */
366 if (tmp->nbytes + last->nbytes < BUFSIZ)
368 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
369 last->nbytes += tmp->nbytes;
373 /* If there's not enough room, link the new buffer onto the end of
374 the list, then either free up the oldest buffer for the next
375 read if that would leave enough characters, or else malloc a new
376 one. Some compaction mechanism is possible but probably not
378 last = last->next = tmp;
379 if (total_bytes - first->nbytes > n_bytes)
382 total_bytes -= first->nbytes;
387 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
391 if (tmp->nbytes == -1)
393 error (0, errno, "%s", filename);
401 /* Run through the list, printing characters. First, skip over unneeded
403 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
404 total_bytes -= tmp->nbytes;
406 /* Find the correct beginning, then print the rest of the file.
407 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
408 if (total_bytes > n_bytes)
409 i = total_bytes - n_bytes;
412 XWRITE (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
414 for (tmp = tmp->next; tmp; tmp = tmp->next)
415 XWRITE (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
421 free ((char *) first);
427 /* Skip N_BYTES characters from the start of pipe FD, and print
428 any extra characters that were read beyond that.
429 Return 1 on error, 0 if ok. */
432 start_bytes (const char *filename, int fd, off_t n_bytes)
437 while (n_bytes > 0 && (bytes_read = fullRead (fd, buffer, BUFSIZ)) > 0)
438 n_bytes -= bytes_read;
439 if (bytes_read == -1)
441 error (0, errno, "%s", filename);
444 else if (n_bytes < 0)
445 XWRITE (STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes);
449 /* Skip N_LINES lines at the start of file or pipe FD, and print
450 any extra characters that were read beyond that.
451 Return 1 on error, 0 if ok. */
454 start_lines (const char *filename, int fd, long int n_lines)
458 int bytes_to_skip = 0;
460 while (n_lines && (bytes_read = fullRead (fd, buffer, BUFSIZ)) > 0)
463 while (bytes_to_skip < bytes_read)
464 if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0)
467 if (bytes_read == -1)
469 error (0, errno, "%s", filename);
472 else if (bytes_to_skip < bytes_read)
474 XWRITE (STDOUT_FILENO, &buffer[bytes_to_skip],
475 bytes_read - bytes_to_skip);
480 /* Display file FILENAME from the current position in FD to the end.
481 If `forever' is nonzero, keep reading from the end of the file
482 until killed. Return the number of bytes read from the file. */
485 dump_remainder (const char *filename, int fd)
493 while ((bytes_read = fullRead (fd, buffer, BUFSIZ)) > 0)
495 XWRITE (STDOUT_FILENO, buffer, bytes_read);
498 if (bytes_read == -1)
499 error (EXIT_FAILURE, errno, "%s", filename);
508 if (forever_multiple)
515 /* Tail NFILES (>1) files forever until killed. The file names are in
516 NAMES. The open file descriptors are in `file_descs', and the size
517 at which we stopped tailing them is in `file_sizes'. We loop over
518 each of them, doing an fstat to see if they have changed size. If
519 none of them have changed size in one iteration, we sleep for a
520 second and try again. We do this until the user interrupts us. */
523 tail_forever (char **names, int nfiles)
535 for (i = 0; i < nfiles; i++)
539 if (file_descs[i] < 0)
541 if (fstat (file_descs[i], &stats) < 0)
543 error (0, errno, "%s", names[i]);
547 if (stats.st_size == file_sizes[i])
550 /* This file has changed size. Print out what we can, and
551 then keep looping. */
555 if (stats.st_size < file_sizes[i])
557 write_header (names[i], "file truncated");
559 lseek (file_descs[i], stats.st_size, SEEK_SET);
560 file_sizes[i] = stats.st_size;
567 write_header (names[i], NULL);
570 file_sizes[i] += dump_remainder (names[i], file_descs[i]);
573 /* If none of the files changed size, sleep. */
579 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
580 Return 0 if successful, 1 if an error occurred. */
583 tail_bytes (const char *filename, int fd, off_t n_bytes)
587 /* FIXME: resolve this like in dd.c. */
588 /* Use fstat instead of checking for errno == ESPIPE because
589 lseek doesn't work on some special files but doesn't return an
591 if (fstat (fd, &stats))
593 error (0, errno, "%s", filename);
599 if (S_ISREG (stats.st_mode))
600 lseek (fd, n_bytes, SEEK_CUR);
601 else if (start_bytes (filename, fd, n_bytes))
603 dump_remainder (filename, fd);
607 if (S_ISREG (stats.st_mode))
609 off_t current_pos, end_pos;
610 size_t bytes_remaining;
612 if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1
613 && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1)
616 /* Be careful here. The current position may actually be
617 beyond the end of the file. */
618 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
622 error (0, errno, "%s", filename);
626 if (bytes_remaining <= n_bytes)
628 /* From the current position to end of file, there are no
629 more bytes than have been requested. So reposition the
630 file pointer to the incoming current position and print
631 everything after that. */
632 lseek (fd, current_pos, SEEK_SET);
636 /* There are more bytes remaining than were requested.
638 lseek (fd, -n_bytes, SEEK_END);
640 dump_remainder (filename, fd);
643 return pipe_bytes (filename, fd, n_bytes);
648 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
649 Return 0 if successful, 1 if an error occurred. */
652 tail_lines (const char *filename, int fd, long int n_lines)
657 if (fstat (fd, &stats))
659 error (0, errno, "%s", filename);
665 if (start_lines (filename, fd, n_lines))
667 dump_remainder (filename, fd);
671 /* Use file_lines only if FD refers to a regular file with
672 its file pointer positioned at beginning of file. */
673 /* FIXME: adding the lseek conjunct is a kludge.
674 Once there's a reasonable test suite, fix the true culprit:
675 file_lines. file_lines shouldn't presume that the input
676 file pointer is initially positioned to beginning of file. */
677 if (S_ISREG (stats.st_mode)
678 && lseek (fd, (off_t) 0, SEEK_CUR) == (off_t) 0)
680 length = lseek (fd, (off_t) 0, SEEK_END);
681 if (length != 0 && file_lines (filename, fd, n_lines, length))
683 dump_remainder (filename, fd);
686 return pipe_lines (filename, fd, n_lines);
691 /* Display the last N_UNITS units of file FILENAME, open for reading
693 Return 0 if successful, 1 if an error occurred. */
696 tail (const char *filename, int fd, off_t n_units)
699 return tail_lines (filename, fd, (long) n_units);
701 return tail_bytes (filename, fd, n_units);
704 /* Display the last N_UNITS units of file FILENAME.
705 "-" for FILENAME means the standard input.
706 FILENUM is this file's index in the list of files the user gave.
707 Return 0 if successful, 1 if an error occurred. */
710 tail_file (const char *filename, off_t n_units, int filenum)
715 if (!strcmp (filename, "-"))
718 filename = "standard input";
720 write_header (filename, NULL);
721 errors = tail (filename, 0, n_units);
722 if (forever_multiple)
724 if (fstat (0, &stats) < 0)
726 error (0, errno, "standard input");
729 else if (!S_ISREG (stats.st_mode))
732 "standard input: cannot follow end of non-regular file");
736 file_descs[filenum] = -1;
739 file_descs[filenum] = 0;
740 file_sizes[filenum] = stats.st_size;
746 /* Not standard input. */
747 fd = open (filename, O_RDONLY);
750 if (forever_multiple)
751 file_descs[filenum] = -1;
752 error (0, errno, "%s", filename);
758 write_header (filename, NULL);
759 errors = tail (filename, fd, n_units);
760 if (forever_multiple)
762 if (fstat (fd, &stats) < 0)
764 error (0, errno, "%s", filename);
767 else if (!S_ISREG (stats.st_mode))
769 error (0, 0, "%s: cannot follow end of non-regular file",
776 file_descs[filenum] = -1;
780 file_descs[filenum] = fd;
781 file_sizes[filenum] = stats.st_size;
788 error (0, errno, "%s", filename);
799 tail_main (int argc, char **argv)
802 enum header_mode header_mode = multiple_files;
804 /* If from_start, the number of items to skip before printing; otherwise,
805 the number of items at the end of the file to print. Initially, -1
806 means the value has not been set. */
811 program_name = argv[0];
814 forever = forever_multiple = from_start = print_headers = 0;
816 /* Parse any options */
817 //fprintf(stderr, "argc=%d, argv=%s\n", argc, *argv);
818 while (--argc > 0 && ( **(++argv) == '-' || **argv == '+' )) {
823 while (stopit == 0 && *(++(*argv))) {
831 n_units = getNum(*(++argv));
845 n_units = atol(*(++argv));
854 header_mode = always;
865 n_units = DEFAULT_N_LINES;
867 /* To start printing with item N_UNITS from the start of the file, skip
868 N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix
869 compatibility it's treated the same as `tail +1'. */
879 if (n_files > 1 && forever)
881 forever_multiple = 1;
883 file_descs = (int *) xmalloc (n_files * sizeof (int));
884 file_sizes = (off_t *) xmalloc (n_files * sizeof (off_t));
887 if (header_mode == always
888 || (header_mode == multiple_files && n_files > 1))
893 exit_status |= tail_file ("-", n_units, 0);
898 for (i = 0; i < n_files; i++)
899 exit_status |= tail_file (file[i], n_units, i);
901 if (forever_multiple)
902 tail_forever (file, n_files);
905 if (have_read_stdin && close (0) < 0)
906 error (EXIT_FAILURE, errno, "-");
907 if (fclose (stdout) == EOF)
908 error (EXIT_FAILURE, errno, "write error");
909 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);