1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989, 90, 91, 1995-2003 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>
40 #include "safe-read.h"
41 #include "xnanosleep.h"
45 /* The official name of this program (e.g., no `g' prefix). */
46 #define PROGRAM_NAME "tail"
49 _("Written by Paul Rubin, David MacKenzie, Ian Lance Taylor, and Jim Meyering.")
52 /* Some systems don't have ENOSYS -- this should be a big enough
53 value that no valid errno value will match it. */
57 /* Number of items to tail. */
58 #define DEFAULT_N_LINES 10
60 /* A special value for dump_remainder's N_BYTES parameter. */
61 #define COPY_TO_EOF OFF_T_MAX
63 /* FIXME: make Follow_name the default? */
64 #define DEFAULT_FOLLOW_MODE Follow_descriptor
68 /* Follow the name of each file: if the file is renamed, try to reopen
69 that name and track the end of the new file if/when it's recreated.
70 This is useful for tracking logs that are occasionally rotated. */
73 /* Follow each descriptor obtained upon opening a file.
74 That means we'll continue to follow the end of a file even after
75 it has been renamed or unlinked. */
79 /* The types of files for which tail works. */
80 #define IS_TAILABLE_FILE_TYPE(Mode) \
81 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISCHR (Mode))
83 static char const *const follow_mode_string[] =
85 "descriptor", "name", 0
88 static enum Follow_mode const follow_mode_map[] =
90 Follow_descriptor, Follow_name,
95 /* The actual file name, or "-" for stdin. */
98 /* File descriptor on which the file is open; -1 if it's not open. */
101 /* The size of the file the last time we checked. */
104 /* The device and inode of the file the last time we checked. */
108 /* The specified name initially referred to a directory or some other
109 type for which tail isn't meaningful. Unlike for a permission problem
110 (tailable, below) once this is set, the name is not checked ever again. */
113 /* See description of DEFAULT_MAX_N_... below. */
114 unsigned int n_unchanged_stats;
116 /* See description of DEFAULT_MAX_N_... below. */
117 unsigned int n_consecutive_size_changes;
119 /* A file is tailable if it exists, is readable, and is of type
120 IS_TAILABLE_FILE_TYPE. */
123 /* The value of errno seen last time we checked this file. */
128 /* Keep trying to open a file even if it is inaccessible when tail starts
129 or if it becomes inaccessible later -- useful only with -f. */
130 static int reopen_inaccessible_files;
132 /* If nonzero, interpret the numeric argument as the number of lines.
133 Otherwise, interpret it as the number of bytes. */
134 static int count_lines;
136 /* Whether we follow the name of each file or the file descriptor
137 that is initially associated with each name. */
138 static enum Follow_mode follow_mode = Follow_descriptor;
140 /* If nonzero, read from the ends of all specified files until killed. */
143 /* If nonzero, count from start of file instead of end. */
144 static int from_start;
146 /* If nonzero, print filename headers. */
147 static int print_headers;
149 /* When to print the filename banners. */
152 multiple_files, always, never
155 /* When tailing a file by name, if there have been this many consecutive
156 iterations for which the size has remained the same, then open/fstat
157 the file to determine if that file name is still associated with the
158 same device/inode-number pair as before. This option is meaningful only
159 when following by name. --max-unchanged-stats=N */
160 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
161 static unsigned long max_n_unchanged_stats_between_opens =
162 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
164 /* This variable is used to ensure that a file that is unlinked or moved
165 aside, yet always growing will be recognized as having been renamed.
166 After detecting this many consecutive size changes for a file, open/fstat
167 the file to determine if that file name is still associated with the
168 same device/inode-number pair as before. This option is meaningful only
169 when following by name. --max-consecutive-size-changes=N */
170 #define DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES 200
171 static unsigned long max_n_consecutive_size_changes_between_opens =
172 DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES;
174 /* The name this program was run with. */
177 /* The process ID of the process (presumably on the current host)
178 that is writing to all followed files. */
181 /* Nonzero if we have ever read standard input. */
182 static int have_read_stdin;
184 /* If nonzero, skip the is-regular-file test used to determine whether
185 to use the lseek optimization. Instead, use the more general (and
186 more expensive) code unconditionally. Intended solely for testing. */
187 static bool presume_input_pipe;
189 /* For long options that have no equivalent short option, use a
190 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
193 RETRY_OPTION = CHAR_MAX + 1,
194 ALLOW_MISSING_OPTION, /* deprecated, FIXME: remove in late 2004 */
195 MAX_UNCHANGED_STATS_OPTION,
197 /* FIXME: remove this in 2001, unless someone can show a good
198 reason to keep it. */
199 MAX_CONSECUTIVE_SIZE_CHANGES_OPTION,
202 PRESUME_INPUT_PIPE_OPTION,
206 static struct option const long_options[] =
208 /* --allow-missing is deprecated; use --retry instead */
209 {"allow-missing", no_argument, NULL, ALLOW_MISSING_OPTION},
210 {"bytes", required_argument, NULL, 'c'},
211 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
212 {"lines", required_argument, NULL, 'n'},
213 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
214 {"max-consecutive-size-changes", required_argument, NULL,
215 MAX_CONSECUTIVE_SIZE_CHANGES_OPTION},
216 {"pid", required_argument, NULL, PID_OPTION},
217 {"presume-input-pipe", no_argument, NULL,
218 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
219 {"quiet", no_argument, NULL, 'q'},
220 {"retry", no_argument, NULL, RETRY_OPTION},
221 {"silent", no_argument, NULL, 'q'},
222 {"sleep-interval", required_argument, NULL, 's'},
223 {"verbose", no_argument, NULL, 'v'},
224 {GETOPT_HELP_OPTION_DECL},
225 {GETOPT_VERSION_OPTION_DECL},
233 fprintf (stderr, _("Try `%s --help' for more information.\n"),
238 Usage: %s [OPTION]... [FILE]...\n\
242 Print the last %d lines of each FILE to standard output.\n\
243 With more than one FILE, precede each with a header giving the file name.\n\
244 With no FILE, or when FILE is -, read standard input.\n\
246 "), DEFAULT_N_LINES);
248 Mandatory arguments to long options are mandatory for short options too.\n\
251 --retry keep trying to open a file even if it is\n\
252 inaccessible when tail starts or if it becomes\n\
253 inaccessible later -- useful only with -f\n\
254 -c, --bytes=N output the last N bytes\n\
257 -f, --follow[={name|descriptor}]\n\
258 output appended data as the file grows;\n\
259 -f, --follow, and --follow=descriptor are\n\
261 -F same as --follow=name --retry\n\
264 -n, --lines=N output the last N lines, instead of the last %d\n\
265 --max-unchanged-stats=N\n\
266 with --follow=name, reopen a FILE which has not\n\
267 changed size after N (default %d) iterations\n\
268 to see if it has been unlinked or renamed\n\
269 (this is the usual case of rotated log files)\n\
272 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
275 --pid=PID with -f, terminate after process ID, PID dies\n\
276 -q, --quiet, --silent never output headers giving file names\n\
277 -s, --sleep-interval=S with -f, sleep for approximately S seconds\n\
278 (default 1.0) between iterations.\n\
279 -v, --verbose always output headers giving file names\n\
281 fputs (HELP_OPTION_DESCRIPTION, stdout);
282 fputs (VERSION_OPTION_DESCRIPTION, stdout);
285 If the first character of N (the number of bytes or lines) is a `+',\n\
286 print beginning with the Nth item from the start of each file, otherwise,\n\
287 print the last N items in the file. N may have a multiplier suffix:\n\
288 b 512, k 1024, m 1024*1024.\n\
292 With --follow (-f), tail defaults to following the file descriptor, which\n\
293 means that even if a tail'ed file is renamed, tail will continue to track\n\
297 This default behavior is not desirable when you really want to\n\
298 track the actual name of the file, not the file descriptor (e.g., log\n\
299 rotation). Use --follow=name in that case. That causes tail to track the\n\
300 named file by reopening it periodically to see if it has been removed and\n\
301 recreated by some other program.\n\
303 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
305 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
309 valid_file_spec (struct File_spec const *f)
311 /* Exactly one of the following subexpressions must be true. */
312 return ((f->fd == -1) ^ (f->errnum == 0));
316 pretty_name (struct File_spec const *f)
318 return (STREQ (f->name, "-") ? "standard input" : f->name);
322 xwrite (int fd, char const *buffer, size_t n_bytes)
324 assert (fd == STDOUT_FILENO);
325 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
326 error (EXIT_FAILURE, errno, _("write error"));
330 close_fd (int fd, const char *filename)
332 if (fd != -1 && fd != STDIN_FILENO && close (fd))
334 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
339 write_header (const char *pretty_filename)
341 static int first_file = 1;
343 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
347 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
348 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
349 Return the number of bytes read from the file. */
352 dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
355 uintmax_t n_remaining = n_bytes;
361 size_t n = MIN (n_remaining, BUFSIZ);
362 size_t bytes_read = safe_read (fd, buffer, n);
363 if (bytes_read == SAFE_READ_ERROR)
364 error (EXIT_FAILURE, errno, _("error reading %s"),
365 quote (pretty_filename));
368 xwrite (STDOUT_FILENO, buffer, bytes_read);
369 n_remaining -= bytes_read;
370 n_written += bytes_read;
376 /* Call lseek with the specified arguments, where file descriptor FD
377 corresponds to the file, FILENAME.
378 Give a diagnostic and exit nonzero if lseek fails.
379 Otherwise, return the resulting offset. */
382 xlseek (int fd, off_t offset, int whence, char const *filename)
384 off_t new_offset = lseek (fd, offset, whence);
385 char buf[INT_BUFSIZE_BOUND (off_t)];
391 s = offtostr (offset, buf);
395 error (0, errno, _("%s: cannot seek to offset %s"),
399 error (0, errno, _("%s: cannot seek to relative offset %s"),
403 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
413 /* Print the last N_LINES lines from the end of file FD.
414 Go backward through the file, reading `BUFSIZ' bytes at a time (except
415 probably the first), until we hit the start of the file or have
416 read NUMBER newlines.
417 START_POS is the starting position of the read pointer for the file
418 associated with FD (may be nonzero).
419 END_POS is the file offset of EOF (one larger than offset of last byte).
420 Return 0 if successful, 1 if an error occurred. */
423 file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
424 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
433 /* Set `bytes_read' to the size of the last, probably partial, buffer;
434 0 < `bytes_read' <= `BUFSIZ'. */
435 bytes_read = (pos - start_pos) % BUFSIZ;
438 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
439 reads will be on block boundaries, which might increase efficiency. */
441 xlseek (fd, pos, SEEK_SET, pretty_filename);
442 bytes_read = safe_read (fd, buffer, bytes_read);
443 if (bytes_read == SAFE_READ_ERROR)
445 error (0, errno, _("error reading %s"), quote (pretty_filename));
448 *read_pos = pos + bytes_read;
450 /* Count the incomplete line on files that don't end with a newline. */
451 if (bytes_read && buffer[bytes_read - 1] != '\n')
456 /* Scan backward, counting the newlines in this bufferfull. */
458 size_t n = bytes_read;
462 nl = memrchr (buffer, '\n', n);
468 /* If this newline isn't the last character in the buffer,
469 output the part that is after it. */
470 if (n != bytes_read - 1)
471 xwrite (STDOUT_FILENO, nl + 1, bytes_read - (n + 1));
472 *read_pos += dump_remainder (pretty_filename, fd,
473 end_pos - (pos + bytes_read));
478 /* Not enough newlines in that bufferfull. */
479 if (pos == start_pos)
481 /* Not enough lines in the file; print everything from
482 start_pos to the end. */
483 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
484 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
489 xlseek (fd, pos, SEEK_SET, pretty_filename);
491 bytes_read = safe_read (fd, buffer, BUFSIZ);
492 if (bytes_read == SAFE_READ_ERROR)
494 error (0, errno, _("error reading %s"), quote (pretty_filename));
498 *read_pos = pos + bytes_read;
500 while (bytes_read > 0);
505 /* Print the last N_LINES lines from the end of the standard input,
506 open for reading as pipe FD.
507 Buffer the text as a linked list of LBUFFERs, adding them as needed.
508 Return 0 if successful, 1 upon error. */
511 pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
519 struct linebuffer *next;
521 typedef struct linebuffer LBUFFER;
522 LBUFFER *first, *last, *tmp;
523 size_t total_lines = 0; /* Total number of newlines in all buffers. */
525 size_t n_read; /* Size in bytes of most recent read */
527 first = last = xmalloc (sizeof (LBUFFER));
528 first->nbytes = first->nlines = 0;
530 tmp = xmalloc (sizeof (LBUFFER));
532 /* Input is always read into a fresh buffer. */
535 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
536 if (n_read == 0 || n_read == SAFE_READ_ERROR)
538 tmp->nbytes = n_read;
543 /* Count the number of newlines just read. */
545 char const *buffer_end = tmp->buffer + n_read;
546 char const *p = tmp->buffer;
547 while ((p = memchr (p, '\n', buffer_end - p)))
553 total_lines += tmp->nlines;
555 /* If there is enough room in the last buffer read, just append the new
556 one to it. This is because when reading from a pipe, `n_read' can
557 often be very small. */
558 if (tmp->nbytes + last->nbytes < BUFSIZ)
560 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
561 last->nbytes += tmp->nbytes;
562 last->nlines += tmp->nlines;
566 /* If there's not enough room, link the new buffer onto the end of
567 the list, then either free up the oldest buffer for the next
568 read if that would leave enough lines, or else malloc a new one.
569 Some compaction mechanism is possible but probably not
571 last = last->next = tmp;
572 if (total_lines - first->nlines > n_lines)
575 total_lines -= first->nlines;
579 tmp = xmalloc (sizeof (LBUFFER));
585 if (n_read == SAFE_READ_ERROR)
587 error (0, errno, _("error reading %s"), quote (pretty_filename));
592 /* If the file is empty, then bail out. */
593 if (last->nbytes == 0)
596 /* This prevents a core dump when the pipe contains no newlines. */
600 /* Count the incomplete line on files that don't end with a newline. */
601 if (last->buffer[last->nbytes - 1] != '\n')
607 /* Run through the list, printing lines. First, skip over unneeded
609 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
610 total_lines -= tmp->nlines;
612 /* Find the correct beginning, then print the rest of the file. */
614 char const *beg = tmp->buffer;
615 char const *buffer_end = tmp->buffer + tmp->nbytes;
616 if (total_lines > n_lines)
618 /* Skip `total_lines' - `n_lines' newlines. We made sure that
619 `total_lines' - `n_lines' <= `tmp->nlines'. */
621 for (j = total_lines - n_lines; j; --j)
623 beg = memchr (beg, '\n', buffer_end - beg);
629 xwrite (STDOUT_FILENO, beg, buffer_end - beg);
632 for (tmp = tmp->next; tmp; tmp = tmp->next)
633 xwrite (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
645 /* Print the last N_BYTES characters from the end of pipe FD.
646 This is a stripped down version of pipe_lines.
647 Return 0 if successful, 1 if an error occurred. */
650 pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
657 struct charbuffer *next;
659 typedef struct charbuffer CBUFFER;
660 CBUFFER *first, *last, *tmp;
661 size_t i; /* Index into buffers. */
662 size_t total_bytes = 0; /* Total characters in all buffers. */
666 first = last = xmalloc (sizeof (CBUFFER));
669 tmp = xmalloc (sizeof (CBUFFER));
671 /* Input is always read into a fresh buffer. */
674 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
675 if (n_read == 0 || n_read == SAFE_READ_ERROR)
678 tmp->nbytes = n_read;
681 total_bytes += tmp->nbytes;
682 /* If there is enough room in the last buffer read, just append the new
683 one to it. This is because when reading from a pipe, `nbytes' can
684 often be very small. */
685 if (tmp->nbytes + last->nbytes < BUFSIZ)
687 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
688 last->nbytes += tmp->nbytes;
692 /* If there's not enough room, link the new buffer onto the end of
693 the list, then either free up the oldest buffer for the next
694 read if that would leave enough characters, or else malloc a new
695 one. Some compaction mechanism is possible but probably not
697 last = last->next = tmp;
698 if (total_bytes - first->nbytes > n_bytes)
701 total_bytes -= first->nbytes;
706 tmp = xmalloc (sizeof (CBUFFER));
713 if (n_read == SAFE_READ_ERROR)
715 error (0, errno, _("error reading %s"), quote (pretty_filename));
720 /* Run through the list, printing characters. First, skip over unneeded
722 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
723 total_bytes -= tmp->nbytes;
725 /* Find the correct beginning, then print the rest of the file.
726 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
727 if (total_bytes > n_bytes)
728 i = total_bytes - n_bytes;
731 xwrite (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
733 for (tmp = tmp->next; tmp; tmp = tmp->next)
734 xwrite (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
746 /* Skip N_BYTES characters from the start of pipe FD, and print
747 any extra characters that were read beyond that.
748 Return 1 on error, 0 if ok, -1 if EOF. */
751 start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
758 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
761 if (bytes_read == SAFE_READ_ERROR)
763 error (0, errno, _("error reading %s"), quote (pretty_filename));
766 read_pos += bytes_read;
767 if (bytes_read <= n_bytes)
768 n_bytes -= bytes_read;
771 size_t n_remaining = bytes_read - n_bytes;
773 xwrite (STDOUT_FILENO, &buffer[n_bytes], n_remaining);
781 /* Skip N_LINES lines at the start of file or pipe FD, and print
782 any extra characters that were read beyond that.
783 Return 1 on error, 0 if ok, -1 if EOF. */
786 start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
796 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
797 char *buffer_end = buffer + bytes_read;
798 if (bytes_read == 0) /* EOF */
800 if (bytes_read == SAFE_READ_ERROR) /* error */
802 error (0, errno, _("error reading %s"), quote (pretty_filename));
806 *read_pos += bytes_read;
808 while ((p = memchr (p, '\n', buffer_end - p)))
814 xwrite (STDOUT_FILENO, p, buffer_end - p);
821 /* FIXME: describe */
824 recheck (struct File_spec *f)
826 /* open/fstat the file and announce if dev/ino have changed */
827 struct stat new_stats;
830 int is_stdin = (STREQ (f->name, "-"));
831 int was_tailable = f->tailable;
832 int prev_errnum = f->errnum;
835 assert (valid_file_spec (f));
837 fd = (is_stdin ? STDIN_FILENO : open (f->name, O_RDONLY));
839 /* If the open fails because the file doesn't exist,
840 then mark the file as not tailable. */
841 f->tailable = !(reopen_inaccessible_files && fd == -1);
843 if (fd == -1 || fstat (fd, &new_stats) < 0)
851 /* FIXME-maybe: detect the case in which the file first becomes
852 unreadable (perms), and later becomes readable again and can
853 be seen to be the same file (dev/ino). Otherwise, tail prints
854 the entire contents of the file when it becomes readable. */
855 error (0, f->errnum, _("`%s' has become inaccessible"),
860 /* say nothing... it's still not tailable */
863 else if (prev_errnum != errno)
865 error (0, errno, "%s", pretty_name (f));
868 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
872 error (0, 0, _("`%s' has been replaced with an untailable file;\
873 giving up on this name"),
885 close_fd (fd, pretty_name (f));
886 close_fd (f->fd, pretty_name (f));
889 else if (prev_errnum && prev_errnum != ENOENT)
892 assert (f->fd == -1);
893 error (0, 0, _("`%s' has become accessible"), pretty_name (f));
895 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
901 _("`%s' has appeared; following end of new file"),
906 /* Close the old one. */
907 close_fd (f->fd, pretty_name (f));
909 /* File has been replaced (e.g., via log rotation) --
912 _("`%s' has been replaced; following end of new file"),
920 /* This happens when one iteration finds the file missing,
921 then the preceding <dev,inode> pair is reused as the
922 file is recreated. */
927 close_fd (fd, pretty_name (f));
933 /* Record new file info in f. */
935 f->size = 0; /* Start at the beginning of the file... */
936 f->dev = new_stats.st_dev;
937 f->ino = new_stats.st_ino;
938 f->n_unchanged_stats = 0;
939 f->n_consecutive_size_changes = 0;
941 xlseek (f->fd, f->size, SEEK_SET, pretty_name (f));
945 /* FIXME: describe */
948 n_live_files (const struct File_spec *f, int n_files)
951 unsigned int n_live = 0;
953 for (i = 0; i < n_files; i++)
961 /* Tail NFILES files forever, or until killed.
962 The pertinent information for each file is stored in an entry of F.
963 Loop over each of them, doing an fstat to see if they have changed size,
964 and an occasional open/fstat to see if any dev/ino pair has changed.
965 If none of them have changed size in one iteration, sleep for a
966 while and try again. Continue until the user interrupts us. */
969 tail_forever (struct File_spec *f, int nfiles, double sleep_interval)
972 int writer_is_dead = 0;
982 for (i = 0; i < nfiles; i++)
995 if (fstat (f[i].fd, &stats) < 0)
999 error (0, errno, "%s", pretty_name (&f[i]));
1003 if (stats.st_size == f[i].size)
1005 f[i].n_consecutive_size_changes = 0;
1006 if ((max_n_unchanged_stats_between_opens
1007 <= f[i].n_unchanged_stats++)
1008 && follow_mode == Follow_name)
1011 f[i].n_unchanged_stats = 0;
1016 /* Ensure that a file that's unlinked or moved aside, yet always
1017 growing will be recognized as having been renamed. */
1018 if ((max_n_consecutive_size_changes_between_opens
1019 <= f[i].n_consecutive_size_changes++)
1020 && follow_mode == Follow_name)
1022 f[i].n_consecutive_size_changes = 0;
1027 /* This file has changed size. Print out what we can, and
1028 then keep looping. */
1033 f[i].n_unchanged_stats = 0;
1035 if (stats.st_size < f[i].size)
1037 error (0, 0, _("%s: file truncated"), pretty_name (&f[i]));
1039 xlseek (f[i].fd, (off_t) stats.st_size, SEEK_SET,
1040 pretty_name (&f[i]));
1041 f[i].size = stats.st_size;
1048 write_header (pretty_name (&f[i]));
1051 f[i].size += dump_remainder (pretty_name (&f[i]), f[i].fd,
1055 if (n_live_files (f, nfiles) == 0 && ! reopen_inaccessible_files)
1057 error (0, 0, _("no files remaining"));
1061 /* If none of the files changed size, sleep. */
1067 if (xnanosleep (sleep_interval))
1068 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1070 /* Once the writer is dead, read the files once more to
1071 avoid a race condition. */
1072 writer_is_dead = (pid != 0
1073 && kill (pid, 0) != 0
1074 /* Handle the case in which you cannot send a
1075 signal to the writer, so kill fails and sets
1082 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1083 Return 0 if successful, 1 if an error occurred. */
1086 tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1087 uintmax_t *read_pos)
1091 /* We need binary input, since `tail' relies on `lseek' and byte counts,
1092 while binary output will preserve the style (Unix/DOS) of text file. */
1093 SET_BINARY2 (fd, STDOUT_FILENO);
1095 if (fstat (fd, &stats))
1097 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1103 if ( ! presume_input_pipe
1104 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1106 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1107 *read_pos += n_bytes;
1112 if ((t = start_bytes (pretty_filename, fd, n_bytes, read_pos)) < 0)
1117 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1121 if ( ! presume_input_pipe
1122 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1124 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1125 off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename);
1126 off_t diff = end_pos - current_pos;
1127 /* Be careful here. The current position may actually be
1128 beyond the end of the file. */
1129 off_t bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
1132 if (bytes_remaining <= nb)
1134 /* From the current position to end of file, there are no
1135 more bytes than have been requested. So reposition the
1136 file pointer to the incoming current position and print
1137 everything after that. */
1138 *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1142 /* There are more bytes remaining than were requested.
1144 *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename);
1146 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1149 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1154 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1155 Return 0 if successful, 1 if an error occurred. */
1158 tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1159 uintmax_t *read_pos)
1163 /* We need binary input, since `tail' relies on `lseek' and byte counts,
1164 while binary output will preserve the style (Unix/DOS) of text file. */
1165 SET_BINARY2 (fd, STDOUT_FILENO);
1167 if (fstat (fd, &stats))
1169 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1176 if ((t = start_lines (pretty_filename, fd, n_lines, read_pos)) < 0)
1180 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1184 off_t start_pos = -1;
1187 /* Use file_lines only if FD refers to a regular file for
1188 which lseek (... SEEK_END) works. */
1189 if ( ! presume_input_pipe
1190 && S_ISREG (stats.st_mode)
1191 && (start_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1
1192 && start_pos < (end_pos = lseek (fd, (off_t) 0, SEEK_END)))
1194 *read_pos = end_pos;
1195 if (end_pos != 0 && file_lines (pretty_filename, fd, n_lines,
1196 start_pos, end_pos, read_pos))
1201 /* Under very unlikely circumstances, it is possible to reach
1202 this point after positioning the file pointer to end of file
1203 via the `lseek (...SEEK_END)' above. In that case, reposition
1204 the file pointer back to start_pos before calling pipe_lines. */
1205 if (start_pos != -1)
1206 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1208 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1214 /* Display the last N_UNITS units of file FILENAME, open for reading
1215 via FD. Set *READ_POS to the position of the input stream pointer.
1216 *READ_POS is usually the number of bytes read and corresponds to an
1217 offset from the beginning of a file. However, it may be larger than
1218 OFF_T_MAX (as for an input pipe), and may also be larger than the
1219 number of bytes read (when an input pointer is initially not at
1220 beginning of file), and may be far greater than the number of bytes
1221 actually read for an input file that is seekable.
1222 Return 0 if successful, 1 if an error occurred. */
1225 tail (const char *filename, int fd, uintmax_t n_units,
1226 uintmax_t *read_pos)
1230 return tail_lines (filename, fd, n_units, read_pos);
1232 return tail_bytes (filename, fd, n_units, read_pos);
1235 /* Display the last N_UNITS units of the file described by F.
1236 Return 0 if successful, 1 if an error occurred. */
1239 tail_file (struct File_spec *f, uintmax_t n_units)
1243 int is_stdin = (STREQ (f->name, "-"));
1247 have_read_stdin = 1;
1252 fd = open (f->name, O_RDONLY);
1255 f->tailable = !(reopen_inaccessible_files && fd == -1);
1267 error (0, errno, _("cannot open %s for reading"),
1268 quote (pretty_name (f)));
1276 write_header (pretty_name (f));
1277 errors = tail (pretty_name (f), fd, n_units, &read_pos);
1282 #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
1283 /* Before the tail function provided `read_pos', there was
1284 a race condition described in the URL below. This sleep
1285 call made the window big enough to exercise the problem. */
1289 if (fstat (fd, &stats) < 0)
1293 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1295 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1297 error (0, 0, _("%s: cannot follow end of this type of file;\
1298 giving up on this name"),
1307 close_fd (fd, pretty_name (f));
1314 /* Note: we must use read_pos here, not stats.st_size,
1315 to avoid a race condition described by Ken Raeburn:
1316 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1318 f->dev = stats.st_dev;
1319 f->ino = stats.st_ino;
1320 f->n_unchanged_stats = 0;
1321 f->n_consecutive_size_changes = 0;
1327 if (!is_stdin && close (fd))
1329 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1338 /* If the command line arguments are of the obsolescent form and the
1339 option string is well-formed, set *FAIL to zero, set *N_UNITS, the
1340 globals COUNT_LINES, FOREVER, and FROM_START, and return non-zero.
1341 Otherwise, if the command line arguments appear to be of the
1342 obsolescent form but the option string is malformed, set *FAIL to
1343 non-zero, don't modify any other parameter or global variable, and
1344 return non-zero. Otherwise, return zero and don't modify any parameter
1345 or global variable. */
1348 parse_obsolescent_option (int argc, const char *const *argv,
1349 uintmax_t *n_units, int *fail)
1351 const char *p = argv[1];
1352 const char *n_string = NULL;
1353 const char *n_string_end;
1354 bool obsolete_usage;
1360 /* With the obsolescent form, there is one option string and
1361 (technically) at most one file argument. But we allow two or more
1366 obsolete_usage = (posix2_version () < 200112);
1368 /* If P starts with `+' and the POSIX version predates 1003.1-2001,
1369 or if P starts with `-N' (where N is a digit), or `-l', then it
1370 is obsolescent. Return zero otherwise. */
1371 if (! ((p[0] == '+' && obsolete_usage)
1372 || (p[0] == '-' && (p[1] == 'l' || ISDIGIT (p[1])))))
1390 while (ISDIGIT (*p));
1395 if (*p == 'c' || *p == 'b')
1414 /* If (argv[1] begins with a `+' or if it begins with `-' followed
1415 by a digit), but has an invalid suffix character, give a diagnostic
1416 and indicate to caller that this *is* of the obsolescent form,
1417 but that it's an invalid option. */
1418 if (t_from_start || n_string)
1421 _("%c: invalid suffix character in obsolescent option"), *p);
1426 /* Otherwise, it might be a valid non-obsolescent option like -n. */
1431 if (n_string == NULL)
1432 *n_units = DEFAULT_N_LINES;
1439 s_err = xstrtoumax (n_string, &end, 10, &tmp,
1440 *n_string_end == 'b' ? "b" : NULL);
1441 if (s_err == LONGINT_OK)
1445 /* Extract a NUL-terminated string for the error message. */
1446 size_t len = n_string_end - n_string;
1447 char *n_string_tmp = xmalloc (len + 1);
1449 strncpy (n_string_tmp, n_string, len);
1450 n_string_tmp[len] = '\0';
1453 _("%s: %s is so large that it is not representable"),
1454 n_string_tmp, (t_count_lines
1455 ? _("number of lines")
1456 : _("number of bytes")));
1457 free (n_string_tmp);
1466 /* When POSIXLY_CORRECT is set, enforce the `at most one
1467 file argument' requirement. */
1468 if (getenv ("POSIXLY_CORRECT"))
1471 too many arguments; When using tail's obsolescent option syntax (%s)\n\
1472 there may be no more than one file argument. Use the equivalent -n or -c\n\
1473 option instead."), argv[1]);
1478 #if DISABLED /* FIXME: enable or remove this warning. */
1480 Warning: it is not portable to use two or more file arguments with\n\
1481 tail's obsolescent option syntax (%s). Use the equivalent -n or -c\n\
1482 option instead."), argv[1]);
1486 if (! obsolete_usage)
1488 error (0, 0, _("`%s' option is obsolete; use `%s-%c %.*s'"),
1489 argv[1], t_forever ? " -f" : "", t_count_lines ? 'n' : 'c',
1490 (int) (n_string_end - n_string), n_string);
1491 usage (EXIT_FAILURE);
1495 from_start = t_from_start;
1496 count_lines = t_count_lines;
1497 forever = t_forever;
1504 parse_options (int argc, char **argv,
1505 uintmax_t *n_units, enum header_mode *header_mode,
1506 double *sleep_interval)
1511 forever = from_start = print_headers = 0;
1513 while ((c = getopt_long (argc, argv, "c:n:fFqs:v", long_options, NULL))
1523 follow_mode = Follow_name;
1524 reopen_inaccessible_files = 1;
1529 count_lines = (c == 'n');
1532 else if (*optarg == '-')
1537 s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkm");
1538 if (s_err != LONGINT_OK)
1540 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1542 ? _("invalid number of lines")
1543 : _("invalid number of bytes")));
1549 case LONG_FOLLOW_OPTION:
1552 follow_mode = DEFAULT_FOLLOW_MODE;
1554 follow_mode = XARGMATCH ("--follow", optarg,
1555 follow_mode_string, follow_mode_map);
1558 case ALLOW_MISSING_OPTION:
1560 _("the --allow-missing option is deprecated; use --retry instead"));
1563 reopen_inaccessible_files = 1;
1566 case MAX_UNCHANGED_STATS_OPTION:
1567 /* --max-unchanged-stats=N */
1568 if (xstrtoul (optarg, NULL, 10,
1569 &max_n_unchanged_stats_between_opens, "") != LONGINT_OK)
1571 error (EXIT_FAILURE, 0,
1572 _("%s: invalid maximum number of unchanged stats between opens"),
1577 case MAX_CONSECUTIVE_SIZE_CHANGES_OPTION:
1578 /* --max-consecutive-size-changes=N */
1579 if (xstrtoul (optarg, NULL, 10,
1580 &max_n_consecutive_size_changes_between_opens, "")
1583 error (EXIT_FAILURE, 0,
1584 _("%s: invalid maximum number of consecutive size changes"),
1592 unsigned long int tmp_ulong;
1593 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1594 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1596 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1602 case PRESUME_INPUT_PIPE_OPTION:
1603 presume_input_pipe = true;
1607 *header_mode = never;
1613 if (xstrtod (optarg, NULL, &s) || ! (0 <= s))
1614 error (EXIT_FAILURE, 0,
1615 _("%s: invalid number of seconds"), optarg);
1616 *sleep_interval = s;
1621 *header_mode = always;
1624 case_GETOPT_HELP_CHAR;
1626 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, WRITTEN_BY);
1629 usage (EXIT_FAILURE);
1633 if (reopen_inaccessible_files && follow_mode != Follow_name)
1634 error (0, 0, _("warning: --retry is useful only when following by name"));
1636 if (pid && !forever)
1638 _("warning: PID ignored; --pid=PID is useful only when following"));
1639 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
1641 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1647 main (int argc, char **argv)
1649 enum header_mode header_mode = multiple_files;
1650 int exit_status = 0;
1651 /* If from_start, the number of items to skip before printing; otherwise,
1652 the number of items at the end of the file to print. Although the type
1653 is signed, the value is never negative. */
1654 uintmax_t n_units = DEFAULT_N_LINES;
1657 struct File_spec *F;
1660 /* The number of seconds to sleep between iterations.
1661 During one iteration, every file name or descriptor is checked to
1662 see if it has changed. */
1663 double sleep_interval = 1.0;
1665 initialize_main (&argc, &argv);
1666 program_name = argv[0];
1667 setlocale (LC_ALL, "");
1668 bindtextdomain (PACKAGE, LOCALEDIR);
1669 textdomain (PACKAGE);
1671 atexit (close_stdout);
1673 have_read_stdin = 0;
1678 if (parse_obsolescent_option (argc,
1679 (const char *const *) argv,
1683 exit (EXIT_FAILURE);
1688 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
1692 /* To start printing with item N_UNITS from the start of the file, skip
1693 N_UNITS - 1 items. `tail -n +0' is actually meaningless, but for Unix
1694 compatibility it's treated the same as `tail -n +1'. */
1704 n_files = argc - optind;
1705 file = argv + optind;
1709 static char *dummy_stdin = "-";
1711 file = &dummy_stdin;
1714 F = xmalloc (n_files * sizeof (F[0]));
1715 for (i = 0; i < n_files; i++)
1716 F[i].name = file[i];
1718 if (header_mode == always
1719 || (header_mode == multiple_files && n_files > 1))
1722 for (i = 0; i < n_files; i++)
1723 exit_status |= tail_file (&F[i], n_units);
1727 /* This fflush appears to be required only on Solaris 5.7. */
1728 if (fflush (stdout) < 0)
1729 error (EXIT_FAILURE, errno, _("write error"));
1731 SETVBUF (stdout, NULL, _IONBF, 0);
1732 tail_forever (F, n_files, sleep_interval);
1735 if (have_read_stdin && close (STDIN_FILENO) < 0)
1736 error (EXIT_FAILURE, errno, "-");
1737 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);