1 /* tail -- output the last part of file(s)
2 Copyright (C) 89, 90, 91, 1995-1999 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 Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* Can display any amount of data, unlike the Unix version, which uses
19 a fixed size buffer and therefore can only deliver a limited number
22 Original version by Paul Rubin <phr@ocf.berkeley.edu>.
23 Extensions by David MacKenzie <djm@gnu.ai.mit.edu>.
24 tail -f for multiple files by Ian Lance Taylor <ian@airs.com>. */
31 #include <sys/types.h>
36 #include "safe-read.h"
39 /* The official name of this program (e.g., no `g' prefix). */
40 #define PROGRAM_NAME "tail"
43 "Paul Rubin, David MacKenzie, Ian Lance Taylor, and Jim Meyering"
46 # define OFF_T_MIN TYPE_MINIMUM (off_t)
50 # define OFF_T_MAX TYPE_MAXIMUM (off_t)
53 /* Number of items to tail. */
54 #define DEFAULT_N_LINES 10
56 /* Size of atomic reads. */
58 # define BUFSIZ (512 * 8)
61 /* A special value for dump_remainder's N_BYTES parameter. */
62 #define COPY_TO_EOF OFF_T_MAX
64 /* FIXME: make Follow_name the default? */
65 #define DEFAULT_FOLLOW_MODE Follow_descriptor
69 /* Follow the name of each file: if the file is renamed, try to reopen
70 that name and track the end of the new file if/when it's recreated.
71 This is useful for tracking logs that are occasionally rotated. */
74 /* Follow each descriptor obtained upon opening a file.
75 That means we'll continue to follow the end of a file even after
76 it has been renamed or unlinked. */
77 Follow_descriptor = 2,
80 static char const *const follow_mode_string[] =
82 "descriptor", "name", 0
85 static enum Follow_mode const follow_mode_map[] =
87 Follow_descriptor, Follow_name,
92 /* The actual file name, or "-" for stdin. */
95 /* File descriptor on which the file is open; -1 if it's not open. */
98 /* The size of the file the last time we checked. */
101 /* The device and inode of the file the last time we checked. */
105 /* FIXME: describe */
106 unsigned int n_stat_calls;
108 /* FIXME: describe */
109 unsigned int n_unchanged_stats;
111 /* FIXME: describe */
112 unsigned int n_consecutive_size_changes;
114 /* A file is tailable if it is a regular file or a fifo and it is
118 /* The value of errno seen last time we checked this file. */
123 /* FIXME: describe */
124 static int reopen_inaccessible_files;
126 /* If nonzero, interpret the numeric argument as the number of lines.
127 Otherwise, interpret it as the number of bytes. */
128 static int count_lines;
130 /* Whether we follow the name of each file or the file descriptor
131 that is initially associated with each name. */
132 static enum Follow_mode follow_mode = Follow_descriptor;
134 /* If nonzero, read from the ends of all specified files until killed. */
137 /* If nonzero, count from start of file instead of end. */
138 static int from_start;
140 /* If nonzero, print filename headers. */
141 static int print_headers;
143 /* When to print the filename banners. */
146 multiple_files, always, never
149 /* When tailing a file by name, if there have been this many consecutive
150 iterations for which the size has remained the same, then open/fstat
151 the file to determine if that file name is still associated with the
152 same device/inode-number pair as before. This option is meaningful only
153 when following by name. --max-unchanged-stats=N */
154 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
155 static unsigned long max_n_unchanged_stats_between_opens =
156 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
158 /* This variable is used to ensure that a file that is unlinked or moved
159 aside, yet always growing will be recognized as having been renamed.
160 After detecting this many consecutive size changes for a file, open/fstat
161 the file to determine if that file name is still associated with the
162 same device/inode-number pair as before. This option is meaningful only
163 when following by name. --max-consecutive-size-changes=N */
164 #define DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES 200
165 static unsigned long max_n_consecutive_size_changes_between_opens =
166 DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES;
168 /* The name this program was run with. */
171 /* The number of seconds to sleep between iterations.
172 During one iteration, every file name or descriptor is checked to
173 see if it has changed. */
174 /* FIXME: allow fractional seconds */
175 static unsigned int sleep_interval = 1;
177 /* Nonzero if we have ever read standard input. */
178 static int have_read_stdin;
180 static struct option const long_options[] =
182 /* --allow-missing is deprecated; use --retry instead
183 FIXME: remove it some day */
184 {"allow-missing", no_argument, NULL, CHAR_MAX + 1},
185 {"bytes", required_argument, NULL, 'c'},
186 {"follow", optional_argument, NULL, 'f'},
187 {"lines", required_argument, NULL, 'n'},
188 {"max-unchanged-stats", required_argument, NULL, CHAR_MAX + 2},
189 {"max-consecutive-size-changes", required_argument, NULL, CHAR_MAX + 3},
190 {"quiet", no_argument, NULL, 'q'},
191 {"retry", no_argument, NULL, CHAR_MAX + 1},
192 {"silent", no_argument, NULL, 'q'},
193 {"sleep-interval", required_argument, NULL, 's'},
194 {"verbose", no_argument, NULL, 'v'},
195 {GETOPT_HELP_OPTION_DECL},
196 {GETOPT_VERSION_OPTION_DECL},
204 fprintf (stderr, _("Try `%s --help' for more information.\n"),
209 Usage: %s [OPTION]... [FILE]...\n\
213 Print the last %d lines of each FILE to standard output.\n\
214 With more than one FILE, precede each with a header giving the file name.\n\
215 With no FILE, or when FILE is -, read standard input.\n\
217 --retry keep trying to open a file even if it is\n\
218 inaccessible when tail starts or if it becomes\n\
219 inaccessible later -- useful only with -f\n\
220 -c, --bytes=N output the last N bytes\n\
221 -f, --follow[={name|descriptor}] output appended data as the file grows;\n\
222 -f, --follow, and --follow=descriptor are\n\
224 -n, --lines=N output the last N lines, instead of the last %d\n\
225 --max-unchanged-stats=N see the texinfo documentation\n\
226 (the default is %d)\n\
227 --max-consecutive-size-changes=N see the texinfo documentation\n\
228 (the default is %d)\n\
229 -q, --quiet, --silent never output headers giving file names\n\
230 -s, --sleep-interval=S with -f, sleep S seconds between iterations\n\
231 -v, --verbose always output headers giving file names\n\
232 --help display this help and exit\n\
233 --version output version information and exit\n\
235 If the first character of N (the number of bytes or lines) is a `+',\n\
236 print beginning with the Nth item from the start of each file, otherwise,\n\
237 print the last N items in the file. N may have a multiplier suffix:\n\
238 b for 512, k for 1024, m for 1048576 (1 Meg). A first OPTION of -VALUE\n\
239 or +VALUE is treated like -n VALUE or -n +VALUE unless VALUE has one of\n\
240 the [bkm] suffix multipliers, in which case it is treated like -c VALUE\n\
243 With --follow (-f), tail defaults to following the file descriptor, which\n\
244 means that even if a tail'ed file is renamed, tail will continue to track\n\
245 its end. This default behavior is not desirable when you really want to\n\
246 track the actual name of the file, not the file descriptor (e.g., log\n\
247 rotation). Use --follow=name in that case. That causes tail to track the\n\
248 named file by reopening it periodically to see if it has been removed and\n\
249 recreated by some other program.\n\
252 DEFAULT_N_LINES, DEFAULT_N_LINES,
253 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS,
254 DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES
256 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
258 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
262 valid_file_spec (struct File_spec const *f)
264 /* Exactly one of the following subexpressions must be true. */
265 return ((f->fd == -1) ^ (f->errnum == 0));
269 pretty_name (struct File_spec const *f)
271 return (STREQ (f->name, "-") ? "standard input" : f->name);
275 xwrite (int fd, char *const buffer, size_t n_bytes)
277 assert (fd == STDOUT_FILENO);
278 assert (n_bytes >= 0);
279 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
280 error (EXIT_FAILURE, errno, _("write error"));
284 close_fd (int fd, const char *filename)
286 if (fd != -1 && fd != STDIN_FILENO && close (fd))
288 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
293 write_header (const char *pretty_filename, const char *comment)
295 static int first_file = 1;
297 printf ("%s==> %s%s%s <==\n", (first_file ? "" : "\n"), pretty_filename,
298 (comment ? ": " : ""),
299 (comment ? comment : ""));
303 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
304 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
305 Return the number of bytes read from the file. */
308 dump_remainder (const char *pretty_filename, int fd, off_t n_bytes)
313 off_t n_remaining = n_bytes;
318 long n = MIN (n_remaining, (off_t) BUFSIZ);
319 bytes_read = safe_read (fd, buffer, n);
322 xwrite (STDOUT_FILENO, buffer, bytes_read);
323 n_remaining -= bytes_read;
324 n_written += bytes_read;
326 if (bytes_read == -1)
327 error (EXIT_FAILURE, errno, "%s", pretty_filename);
332 /* Print the last N_LINES lines from the end of file FD.
333 Go backward through the file, reading `BUFSIZ' bytes at a time (except
334 probably the first), until we hit the start of the file or have
335 read NUMBER newlines.
336 FILE_LENGTH is the length of the file (one more than the offset of the
337 last byte of the file).
338 Return 0 if successful, 1 if an error occurred. */
341 file_lines (const char *pretty_filename, int fd, long int n_lines,
346 int i; /* Index into `buffer' for scanning. */
347 off_t pos = file_length;
352 /* Set `bytes_read' to the size of the last, probably partial, buffer;
353 0 < `bytes_read' <= `BUFSIZ'. */
354 bytes_read = pos % BUFSIZ;
357 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
358 reads will be on block boundaries, which might increase efficiency. */
360 /* FIXME: check lseek return value */
361 lseek (fd, pos, SEEK_SET);
362 bytes_read = safe_read (fd, buffer, bytes_read);
363 if (bytes_read == -1)
365 error (0, errno, "%s", pretty_filename);
369 /* Count the incomplete line on files that don't end with a newline. */
370 if (bytes_read && buffer[bytes_read - 1] != '\n')
375 /* Scan backward, counting the newlines in this bufferfull. */
376 for (i = bytes_read - 1; i >= 0; i--)
378 /* Have we counted the requested number of newlines yet? */
379 if (buffer[i] == '\n' && n_lines-- == 0)
381 /* If this newline wasn't the last character in the buffer,
382 print the text after it. */
383 if (i != bytes_read - 1)
384 xwrite (STDOUT_FILENO, &buffer[i + 1], bytes_read - (i + 1));
385 dump_remainder (pretty_filename, fd,
386 file_length - (pos + bytes_read));
390 /* Not enough newlines in that bufferfull. */
393 /* Not enough lines in the file; print the entire file. */
394 /* FIXME: check lseek return value */
395 lseek (fd, (off_t) 0, SEEK_SET);
396 dump_remainder (pretty_filename, fd, file_length);
400 /* FIXME: check lseek return value */
401 lseek (fd, pos, SEEK_SET);
403 while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0);
405 if (bytes_read == -1)
407 error (0, errno, "%s", pretty_filename);
414 /* Print the last N_LINES lines from the end of the standard input,
415 open for reading as pipe FD.
416 Buffer the text as a linked list of LBUFFERs, adding them as needed.
417 Return 0 if successful, 1 if an error occured. */
420 pipe_lines (const char *pretty_filename, int fd, long int n_lines)
426 struct linebuffer *next;
428 typedef struct linebuffer LBUFFER;
429 LBUFFER *first, *last, *tmp;
430 int i; /* Index into buffers. */
431 int total_lines = 0; /* Total number of newlines in all buffers. */
434 first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
435 first->nbytes = first->nlines = 0;
437 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
439 /* Input is always read into a fresh buffer. */
440 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
445 /* Count the number of newlines just read. */
446 for (i = 0; i < tmp->nbytes; i++)
447 if (tmp->buffer[i] == '\n')
449 total_lines += tmp->nlines;
451 /* If there is enough room in the last buffer read, just append the new
452 one to it. This is because when reading from a pipe, `nbytes' can
453 often be very small. */
454 if (tmp->nbytes + last->nbytes < BUFSIZ)
456 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
457 last->nbytes += tmp->nbytes;
458 last->nlines += tmp->nlines;
462 /* If there's not enough room, link the new buffer onto the end of
463 the list, then either free up the oldest buffer for the next
464 read if that would leave enough lines, or else malloc a new one.
465 Some compaction mechanism is possible but probably not
467 last = last->next = tmp;
468 if (total_lines - first->nlines > n_lines)
471 total_lines -= first->nlines;
475 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
478 if (tmp->nbytes == -1)
480 error (0, errno, "%s", pretty_filename);
488 /* This prevents a core dump when the pipe contains no newlines. */
492 /* Count the incomplete line on files that don't end with a newline. */
493 if (last->buffer[last->nbytes - 1] != '\n')
499 /* Run through the list, printing lines. First, skip over unneeded
501 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
502 total_lines -= tmp->nlines;
504 /* Find the correct beginning, then print the rest of the file. */
505 if (total_lines > n_lines)
509 /* Skip `total_lines' - `n_lines' newlines. We made sure that
510 `total_lines' - `n_lines' <= `tmp->nlines'. */
512 for (i = total_lines - n_lines; i; --i)
513 while (*cp++ != '\n')
515 i = cp - tmp->buffer;
519 xwrite (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
521 for (tmp = tmp->next; tmp; tmp = tmp->next)
522 xwrite (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
528 free ((char *) first);
534 /* Print the last N_BYTES characters from the end of pipe FD.
535 This is a stripped down version of pipe_lines.
536 Return 0 if successful, 1 if an error occurred. */
539 pipe_bytes (const char *pretty_filename, int fd, off_t n_bytes)
545 struct charbuffer *next;
547 typedef struct charbuffer CBUFFER;
548 CBUFFER *first, *last, *tmp;
549 int i; /* Index into buffers. */
550 int total_bytes = 0; /* Total characters in all buffers. */
553 first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
556 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
558 /* Input is always read into a fresh buffer. */
559 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
563 total_bytes += tmp->nbytes;
564 /* If there is enough room in the last buffer read, just append the new
565 one to it. This is because when reading from a pipe, `nbytes' can
566 often be very small. */
567 if (tmp->nbytes + last->nbytes < BUFSIZ)
569 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
570 last->nbytes += tmp->nbytes;
574 /* If there's not enough room, link the new buffer onto the end of
575 the list, then either free up the oldest buffer for the next
576 read if that would leave enough characters, or else malloc a new
577 one. Some compaction mechanism is possible but probably not
579 last = last->next = tmp;
580 if (total_bytes - first->nbytes > n_bytes)
583 total_bytes -= first->nbytes;
588 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
592 if (tmp->nbytes == -1)
594 error (0, errno, "%s", pretty_filename);
602 /* Run through the list, printing characters. First, skip over unneeded
604 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
605 total_bytes -= tmp->nbytes;
607 /* Find the correct beginning, then print the rest of the file.
608 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
609 if (total_bytes > n_bytes)
610 i = total_bytes - n_bytes;
613 xwrite (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
615 for (tmp = tmp->next; tmp; tmp = tmp->next)
616 xwrite (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
622 free ((char *) first);
628 /* Skip N_BYTES characters from the start of pipe FD, and print
629 any extra characters that were read beyond that.
630 Return 1 on error, 0 if ok. */
633 start_bytes (const char *pretty_filename, int fd, off_t n_bytes)
638 while (n_bytes > 0 && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
639 n_bytes -= bytes_read;
640 if (bytes_read == -1)
642 error (0, errno, "%s", pretty_filename);
645 else if (n_bytes < 0)
646 xwrite (STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes);
650 /* Skip N_LINES lines at the start of file or pipe FD, and print
651 any extra characters that were read beyond that.
652 Return 1 on error, 0 if ok. */
655 start_lines (const char *pretty_filename, int fd, long int n_lines)
659 int bytes_to_skip = 0;
661 while (n_lines && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
664 while (bytes_to_skip < bytes_read)
665 if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0)
668 if (bytes_read == -1)
670 error (0, errno, "%s", pretty_filename);
673 else if (bytes_to_skip < bytes_read)
675 xwrite (STDOUT_FILENO, &buffer[bytes_to_skip],
676 bytes_read - bytes_to_skip);
681 /* FIXME: describe */
684 recheck (struct File_spec *f)
686 /* open/fstat the file and announce if dev/ino have changed */
687 struct stat new_stats;
690 int is_stdin = (STREQ (f->name, "-"));
691 int was_tailable = f->tailable;
692 int prev_errnum = f->errnum;
695 assert (valid_file_spec (f));
697 fd = (is_stdin ? STDIN_FILENO : open (f->name, O_RDONLY));
699 /* If the open fails because the file doesn't exist,
700 then mark the file as not tailable. */
701 f->tailable = !(reopen_inaccessible_files && fd == -1);
703 if (fd == -1 || fstat (fd, &new_stats) < 0)
711 /* FIXME-maybe: detect the case in which the file first becomes
712 unreadable (perms), and later becomes readable again and can
713 be seen to be the same file (dev/ino). Otherwise, tail prints
714 the entire contents of the file when it becomes readable. */
715 error (0, f->errnum, _("`%s' has become inaccessible"),
720 /* say nothing... it's still not tailable */
723 else if (prev_errnum != errno)
725 error (0, errno, "%s", pretty_name (f));
728 else if (!S_ISREG (new_stats.st_mode)
729 && !S_ISFIFO (new_stats.st_mode))
734 _("`%s' has been replaced with a non-regular file; \
735 cannot follow end of non-regular file"),
746 close_fd (fd, pretty_name (f));
747 close_fd (f->fd, pretty_name (f));
750 else if (prev_errnum && prev_errnum != ENOENT)
753 assert (f->fd == -1);
754 error (0, 0, _("`%s' has become accessible"), pretty_name (f));
756 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
762 _("`%s' has appeared; following end of new file"),
767 /* Close the old one. */
768 close_fd (f->fd, pretty_name (f));
770 /* File has been replaced (e.g., via log rotation) --
773 _("`%s' has been replaced; following end of new file"),
779 close_fd (fd, pretty_name (f));
784 /* Record new file info in f. */
786 f->size = 0; /* Start at the beginning of the file... */
787 f->dev = new_stats.st_dev;
788 f->ino = new_stats.st_ino;
789 f->n_unchanged_stats = 0;
790 f->n_consecutive_size_changes = 0;
791 /* FIXME: check lseek return value */
792 lseek (f->fd, f->size, SEEK_SET);
796 /* FIXME: describe */
799 n_live_files (const struct File_spec *f, int n_files)
802 unsigned int n_live = 0;
804 for (i = 0; i < n_files; i++)
812 /* Tail NFILES files forever, or until killed.
813 The pertinent information for each file is stored in an entry of F.
814 Loop over each of them, doing an fstat to see if they have changed size,
815 and an occasional open/fstat to see if any dev/ino pair has changed.
816 If none of them have changed size in one iteration, sleep for a
817 while and try again. Continue until the user interrupts us. */
820 tail_forever (struct File_spec *f, int nfiles)
832 for (i = 0; i < nfiles; i++)
842 if (fstat (f[i].fd, &stats) < 0)
844 error (0, errno, "%s", pretty_name (&f[i]));
850 if (stats.st_size == f[i].size)
852 f[i].n_consecutive_size_changes = 0;
853 if (++f[i].n_unchanged_stats > max_n_unchanged_stats_between_opens
854 && follow_mode == Follow_name)
857 f[i].n_unchanged_stats = 0;
864 ++f[i].n_consecutive_size_changes;
866 /* Ensure that a file that's unlinked or moved aside, yet always
867 growing will be recognized as having been renamed. */
868 if (follow_mode == Follow_name
869 && (f[i].n_consecutive_size_changes
870 > max_n_consecutive_size_changes_between_opens))
872 f[i].n_consecutive_size_changes = 0;
876 /* This file has changed size. Print out what we can, and
877 then keep looping. */
882 f[i].n_unchanged_stats = 0;
884 if (stats.st_size < f[i].size)
886 write_header (pretty_name (&f[i]), _("file truncated"));
888 /* FIXME: check lseek return value */
889 lseek (f[i].fd, stats.st_size, SEEK_SET);
890 f[i].size = stats.st_size;
897 write_header (pretty_name (&f[i]), NULL);
900 f[i].size += dump_remainder (pretty_name (&f[i]), f[i].fd,
904 if (n_live_files (f, nfiles) == 0 && ! reopen_inaccessible_files)
906 error (0, 0, _("no files remaining"));
910 /* If none of the files changed size, sleep. */
912 sleep (sleep_interval);
916 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
917 Return 0 if successful, 1 if an error occurred. */
920 tail_bytes (const char *pretty_filename, int fd, off_t n_bytes)
924 /* We need binary input, since `tail' relies on `lseek' and byte counts,
925 while binary output will preserve the style (Unix/DOS) of text file. */
926 SET_BINARY2 (fd, STDOUT_FILENO);
928 if (fstat (fd, &stats))
930 error (0, errno, "%s", pretty_filename);
936 if (S_ISREG (stats.st_mode))
938 /* FIXME: check lseek return value */
939 lseek (fd, n_bytes, SEEK_CUR);
941 else if (start_bytes (pretty_filename, fd, n_bytes))
945 dump_remainder (pretty_filename, fd, COPY_TO_EOF);
949 if (S_ISREG (stats.st_mode))
951 off_t current_pos, end_pos;
952 size_t bytes_remaining;
954 if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1
955 && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1)
958 /* Be careful here. The current position may actually be
959 beyond the end of the file. */
960 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
964 error (0, errno, "%s", pretty_filename);
968 if (bytes_remaining <= n_bytes)
970 /* From the current position to end of file, there are no
971 more bytes than have been requested. So reposition the
972 file pointer to the incoming current position and print
973 everything after that. */
974 /* FIXME: check lseek return value */
975 lseek (fd, current_pos, SEEK_SET);
979 /* There are more bytes remaining than were requested.
981 /* FIXME: check lseek return value */
982 lseek (fd, -n_bytes, SEEK_END);
984 dump_remainder (pretty_filename, fd, n_bytes);
987 return pipe_bytes (pretty_filename, fd, n_bytes);
992 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
993 Return 0 if successful, 1 if an error occurred. */
996 tail_lines (const char *pretty_filename, int fd, long int n_lines)
1001 /* We need binary input, since `tail' relies on `lseek' and byte counts,
1002 while binary output will preserve the style (Unix/DOS) of text file. */
1003 SET_BINARY2 (fd, STDOUT_FILENO);
1005 if (fstat (fd, &stats))
1007 error (0, errno, "%s", pretty_filename);
1013 if (start_lines (pretty_filename, fd, n_lines))
1015 dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1019 /* Use file_lines only if FD refers to a regular file with
1020 its file pointer positioned at beginning of file. */
1021 /* FIXME: adding the lseek conjunct is a kludge.
1022 Once there's a reasonable test suite, fix the true culprit:
1023 file_lines. file_lines shouldn't presume that the input
1024 file pointer is initially positioned to beginning of file. */
1025 if (S_ISREG (stats.st_mode)
1026 && lseek (fd, (off_t) 0, SEEK_CUR) == (off_t) 0)
1028 length = lseek (fd, (off_t) 0, SEEK_END);
1029 if (length != 0 && file_lines (pretty_filename, fd, n_lines, length))
1033 return pipe_lines (pretty_filename, fd, n_lines);
1038 /* Display the last N_UNITS units of file FILENAME, open for reading
1040 Return 0 if successful, 1 if an error occurred. */
1043 tail (const char *pretty_filename, int fd, off_t n_units)
1046 return tail_lines (pretty_filename, fd, (long) n_units);
1048 return tail_bytes (pretty_filename, fd, n_units);
1051 /* Display the last N_UNITS units of the file described by F.
1052 Return 0 if successful, 1 if an error occurred. */
1055 tail_file (struct File_spec *f, off_t n_units)
1060 int is_stdin = (STREQ (f->name, "-"));
1064 have_read_stdin = 1;
1069 fd = open (f->name, O_RDONLY);
1072 f->tailable = !(reopen_inaccessible_files && fd == -1);
1081 error (0, errno, "%s", pretty_name (f));
1087 write_header (pretty_name (f), NULL);
1088 errors = tail (pretty_name (f), fd, n_units);
1092 /* FIXME: duplicate code */
1093 if (fstat (fd, &stats) < 0)
1095 error (0, errno, "%s", pretty_name (f));
1099 else if (!S_ISREG (stats.st_mode) && !S_ISFIFO (stats.st_mode))
1101 error (0, 0, _("%s: cannot follow end of non-regular file"),
1108 close_fd (fd, pretty_name (f));
1114 f->size = stats.st_size;
1115 f->dev = stats.st_dev;
1116 f->ino = stats.st_ino;
1117 f->n_unchanged_stats = 0;
1118 f->n_consecutive_size_changes = 0;
1123 if (!is_stdin && close (fd))
1125 error (0, errno, "%s", pretty_name (f));
1134 /* If the command line arguments are of the obsolescent form and the
1135 option string is well-formed, set *FAIL to zero, set *N_UNITS, the
1136 globals COUNT_LINES, FOREVER, and FROM_START, and return non-zero.
1137 Otherwise, if the command line arguments appear to be of the
1138 obsolescent form but the option string is malformed, set *FAIL to
1139 non-zero, don't modify any other parameter or global variable, and
1140 return non-zero. Otherwise, return zero and don't modify any parameter
1141 or global variable. */
1144 parse_obsolescent_option (int argc, const char *const *argv,
1145 off_t *n_units, int *fail)
1147 const char *p = argv[1];
1148 const char *n_string = NULL;
1149 const char *n_string_end;
1155 /* With the obsolescent form, there is one option string and
1156 (technically) at most one file argument. But we allow two or more
1161 /* If P starts with `+', `-N' (where N is a digit), or `-l',
1162 then it is obsolescent. Return zero otherwise. */
1163 if ( ! (p[0] == '+' || (p[0] == '-' && (p[1] == 'l' || ISDIGIT (p[1])))) )
1181 while (ISDIGIT (*p));
1205 /* If (argv[1] begins with a `+' or if it begins with `-' followed
1206 by a digit), but has an invalid suffix character, give a diagnostic
1207 and indicate to caller that this *is* of the obsolescent form,
1208 but that it's an invalid option. */
1209 if (t_from_start || n_string)
1212 _("%c: invalid suffix character in obsolescent option" ), *p);
1217 /* Otherwise, it might be a valid non-obsolescent option like -n. */
1222 if (n_string == NULL)
1223 *n_units = DEFAULT_N_LINES;
1227 unsigned long int tmp_ulong;
1229 s_err = xstrtoul (n_string, &end, 10, &tmp_ulong, NULL);
1230 if (s_err == LONGINT_OK && tmp_ulong <= OFF_T_MAX)
1231 *n_units = (off_t) tmp_ulong;
1234 /* Extract a NUL-terminated string for the error message. */
1235 size_t len = n_string_end - n_string;
1236 char *n_string_tmp = xmalloc (len + 1);
1238 strncpy (n_string_tmp, n_string, len);
1239 n_string_tmp[len] = '\0';
1242 _("%s: %s is so large that it is not representable"),
1243 n_string_tmp, (count_lines
1244 ? _("number of lines")
1245 : _("number of bytes")));
1246 free (n_string_tmp);
1255 int posix_pedantic = (getenv ("POSIXLY_CORRECT") != NULL);
1257 /* When POSIXLY_CORRECT is set, enforce the `at most one
1258 file argument' requirement. */
1262 too many arguments; When using tail's obsolescent option syntax (%s)\n\
1263 there may be no more than one file argument. Use the equivalent -n or -c\n\
1264 option instead."), argv[1]);
1269 #if DISABLED /* FIXME: enable or remove this warning. */
1271 Warning: it is not portable to use two or more file arguments with\n\
1272 tail's obsolescent option syntax (%s). Use the equivalent -n or -c\n\
1273 option instead."), argv[1]);
1278 from_start = t_from_start;
1279 count_lines = t_count_lines;
1280 forever = t_forever;
1287 parse_options (int argc, char **argv,
1288 off_t *n_units, enum header_mode *header_mode)
1293 forever = from_start = print_headers = 0;
1295 while ((c = getopt_long (argc, argv, "c:n:f::qs:v", long_options, NULL))
1305 count_lines = (c == 'n');
1308 else if (*optarg == '-')
1313 unsigned long int tmp_ulong;
1314 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "bkm");
1315 if (s_err == LONGINT_INVALID)
1317 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1319 ? _("invalid number of lines")
1320 : _("invalid number of bytes")));
1322 if (s_err != LONGINT_OK || tmp_ulong > OFF_T_MAX)
1324 error (EXIT_FAILURE, 0,
1325 _("%s: %s is so large that it is not representable"),
1327 c == 'n' ? _("number of lines") : _("number of bytes"));
1329 *n_units = (off_t) tmp_ulong;
1336 follow_mode = DEFAULT_FOLLOW_MODE;
1338 follow_mode = XARGMATCH ("--follow", optarg,
1339 follow_mode_string, follow_mode_map);
1343 reopen_inaccessible_files = 1;
1347 /* --max-unchanged-stats=N */
1348 if (xstrtoul (optarg, NULL, 10,
1349 &max_n_unchanged_stats_between_opens, "") != LONGINT_OK)
1351 error (EXIT_FAILURE, 0,
1352 _("%s: invalid maximum number of unchanged stats between opens"),
1358 /* --max-consecutive-size-changes=N */
1359 if (xstrtoul (optarg, NULL, 10,
1360 &max_n_consecutive_size_changes_between_opens, "")
1363 error (EXIT_FAILURE, 0,
1364 _("%s: invalid maximum number of consecutive size changes"),
1370 *header_mode = never;
1376 unsigned long int tmp_ulong;
1377 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1378 if (s_err != LONGINT_OK || tmp_ulong > UINT_MAX)
1380 error (EXIT_FAILURE, 0,
1381 _("%s: invalid number of seconds"), optarg);
1383 sleep_interval = tmp_ulong;
1388 *header_mode = always;
1391 case_GETOPT_HELP_CHAR;
1393 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1400 if (reopen_inaccessible_files && follow_mode != Follow_name)
1401 error (0, 0, _("warning: --retry is useful only when following by name"));
1405 main (int argc, char **argv)
1407 enum header_mode header_mode = multiple_files;
1408 int exit_status = 0;
1409 /* If from_start, the number of items to skip before printing; otherwise,
1410 the number of items at the end of the file to print. Although the type
1411 is signed, the value is never negative. */
1412 off_t n_units = DEFAULT_N_LINES;
1415 struct File_spec *F;
1418 program_name = argv[0];
1419 setlocale (LC_ALL, "");
1420 bindtextdomain (PACKAGE, LOCALEDIR);
1421 textdomain (PACKAGE);
1423 have_read_stdin = 0;
1426 int found_obsolescent;
1428 found_obsolescent = parse_obsolescent_option (argc,
1429 (const char *const *) argv,
1431 if (found_obsolescent)
1434 exit (EXIT_FAILURE);
1439 parse_options (argc, argv, &n_units, &header_mode);
1443 /* To start printing with item N_UNITS from the start of the file, skip
1444 N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix
1445 compatibility it's treated the same as `tail +1'. */
1452 n_files = argc - optind;
1453 file = argv + optind;
1457 static char *dummy_stdin = "-";
1459 file = &dummy_stdin;
1462 F = (struct File_spec *) xmalloc (n_files * sizeof (F[0]));
1463 for (i = 0; i < n_files; i++)
1464 F[i].name = file[i];
1466 if (header_mode == always
1467 || (header_mode == multiple_files && n_files > 1))
1470 for (i = 0; i < n_files; i++)
1471 exit_status |= tail_file (&F[i], n_units);
1475 SETVBUF (stdout, NULL, _IONBF, 0);
1476 tail_forever (F, n_files);
1479 if (have_read_stdin && close (0) < 0)
1480 error (EXIT_FAILURE, errno, "-");
1481 if (fclose (stdout) == EOF)
1482 error (EXIT_FAILURE, errno, _("write error"));
1483 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);