1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989, 90, 91, 1995-2001 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>
38 #include "safe-read.h"
41 /* The official name of this program (e.g., no `g' prefix). */
42 #define PROGRAM_NAME "tail"
45 "Paul Rubin, David MacKenzie, Ian Lance Taylor, and Jim Meyering"
48 /* Some systems don't have ENOSYS -- this should be a big enough
49 value that no valid errno value will match it. */
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. */
80 /* The types of files for which tail works. */
81 #define IS_TAILABLE_FILE_TYPE(Mode) \
82 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISCHR (Mode))
84 static char const *const follow_mode_string[] =
86 "descriptor", "name", 0
89 static enum Follow_mode const follow_mode_map[] =
91 Follow_descriptor, Follow_name,
96 /* The actual file name, or "-" for stdin. */
99 /* File descriptor on which the file is open; -1 if it's not open. */
102 /* The size of the file the last time we checked. */
105 /* The device and inode of the file the last time we checked. */
109 /* The specified name initially referred to a directory or some other
110 type for which tail isn't meaningful. Unlike for a permission problem
111 (tailable, below) once this is set, the name is not checked ever again. */
114 /* See description of DEFAULT_MAX_N_... below. */
115 unsigned int n_unchanged_stats;
117 /* See description of DEFAULT_MAX_N_... below. */
118 unsigned int n_consecutive_size_changes;
120 /* A file is tailable if it exists, is readable, and is of type
121 IS_TAILABLE_FILE_TYPE. */
124 /* The value of errno seen last time we checked this file. */
129 /* Keep trying to open a file even if it is inaccessible when tail starts
130 or if it becomes inaccessible later -- useful only with -f. */
131 static int reopen_inaccessible_files;
133 /* If nonzero, interpret the numeric argument as the number of lines.
134 Otherwise, interpret it as the number of bytes. */
135 static int count_lines;
137 /* Whether we follow the name of each file or the file descriptor
138 that is initially associated with each name. */
139 static enum Follow_mode follow_mode = Follow_descriptor;
141 /* If nonzero, read from the ends of all specified files until killed. */
144 /* If nonzero, count from start of file instead of end. */
145 static int from_start;
147 /* If nonzero, print filename headers. */
148 static int print_headers;
150 /* When to print the filename banners. */
153 multiple_files, always, never
156 /* When tailing a file by name, if there have been this many consecutive
157 iterations for which the size has remained the same, then open/fstat
158 the file to determine if that file name is still associated with the
159 same device/inode-number pair as before. This option is meaningful only
160 when following by name. --max-unchanged-stats=N */
161 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
162 static unsigned long max_n_unchanged_stats_between_opens =
163 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
165 /* This variable is used to ensure that a file that is unlinked or moved
166 aside, yet always growing will be recognized as having been renamed.
167 After detecting this many consecutive size changes for a file, open/fstat
168 the file to determine if that file name is still associated with the
169 same device/inode-number pair as before. This option is meaningful only
170 when following by name. --max-consecutive-size-changes=N */
171 #define DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES 200
172 static unsigned long max_n_consecutive_size_changes_between_opens =
173 DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES;
175 /* The name this program was run with. */
178 /* The number of seconds to sleep between iterations.
179 During one iteration, every file name or descriptor is checked to
180 see if it has changed. */
181 /* FIXME: allow fractional seconds */
182 static unsigned int sleep_interval = 1;
184 /* The process ID of the process (presumably on the current host)
185 that is writing to all followed files. */
188 /* Nonzero if we have ever read standard input. */
189 static int have_read_stdin;
191 /* For long options that have no equivalent short option, use a
192 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
195 RETRY_OPTION = CHAR_MAX + 1,
196 MAX_UNCHANGED_STATS_OPTION,
198 /* FIXME: remove this in 2001, unless someone can show a good
199 reason to keep it. */
200 MAX_CONSECUTIVE_SIZE_CHANGES_OPTION,
206 static struct option const long_options[] =
208 /* --allow-missing is deprecated; use --retry instead
209 FIXME: remove it some day */
210 {"allow-missing", no_argument, NULL, RETRY_OPTION},
211 {"bytes", required_argument, NULL, 'c'},
212 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
213 {"lines", required_argument, NULL, 'n'},
214 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
215 {"max-consecutive-size-changes", required_argument, NULL,
216 MAX_CONSECUTIVE_SIZE_CHANGES_OPTION},
217 {"pid", required_argument, NULL, PID_OPTION},
218 {"quiet", no_argument, NULL, 'q'},
219 {"retry", no_argument, NULL, RETRY_OPTION},
220 {"silent", no_argument, NULL, 'q'},
221 {"sleep-interval", required_argument, NULL, 's'},
222 {"verbose", no_argument, NULL, 'v'},
223 {GETOPT_HELP_OPTION_DECL},
224 {GETOPT_VERSION_OPTION_DECL},
232 fprintf (stderr, _("Try `%s --help' for more information.\n"),
237 Usage: %s [OPTION]... [FILE]...\n\
241 Print the last %d lines of each FILE to standard output.\n\
242 With more than one FILE, precede each with a header giving the file name.\n\
243 With no FILE, or when FILE is -, read standard input.\n\
245 --retry keep trying to open a file even if it is\n\
246 inaccessible when tail starts or if it becomes\n\
247 inaccessible later -- useful only with -f\n\
248 -c, --bytes=N output the last N bytes\n\
249 -f, --follow[={name|descriptor}] output appended data as the file grows;\n\
250 -f, --follow, and --follow=descriptor are\n\
252 -n, --lines=N output the last N lines, instead of the last %d\n\
253 --max-unchanged-stats=N\n\
254 with --follow=name, reopen a FILE which has not\n\
255 changed size after N (default %d) iterations\n\
256 to see if it has been unlinked or renamed\n\
257 (this is the usual case of rotated log files)\n\
258 --pid=PID with -f, terminate after process ID, PID dies\n\
259 -q, --quiet, --silent never output headers giving file names\n\
260 -s, --sleep-interval=S with -f, each iteration lasts approximately S\n\
261 (default 1) seconds\n\
262 -v, --verbose always output headers giving file names\n\
263 --help display this help and exit\n\
264 --version output version information and exit\n\
267 DEFAULT_N_LINES, DEFAULT_N_LINES,
268 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
271 If the first character of N (the number of bytes or lines) is a `+',\n\
272 print beginning with the Nth item from the start of each file, otherwise,\n\
273 print the last N items in the file. N may have a multiplier suffix:\n\
274 b for 512, k for 1024, m for 1048576 (1 Meg). A first OPTION of -VALUE\n\
275 or +VALUE is treated like -n VALUE or -n +VALUE unless VALUE has one of\n\
276 the [bkm] suffix multipliers, in which case it is treated like -c VALUE\n\
277 or -c +VALUE. Warning: a first option of +VALUE is obsolescent, and support\n\
278 for it will be withdrawn.\n\
280 With --follow (-f), tail defaults to following the file descriptor, which\n\
281 means that even if a tail'ed file is renamed, tail will continue to track\n\
282 its end. This default behavior is not desirable when you really want to\n\
283 track the actual name of the file, not the file descriptor (e.g., log\n\
284 rotation). Use --follow=name in that case. That causes tail to track the\n\
285 named file by reopening it periodically to see if it has been removed and\n\
286 recreated by some other program.\n\
289 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
291 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
295 valid_file_spec (struct File_spec const *f)
297 /* Exactly one of the following subexpressions must be true. */
298 return ((f->fd == -1) ^ (f->errnum == 0));
302 pretty_name (struct File_spec const *f)
304 return (STREQ (f->name, "-") ? "standard input" : f->name);
308 xwrite (int fd, char *const buffer, size_t n_bytes)
310 assert (fd == STDOUT_FILENO);
311 assert (n_bytes >= 0);
312 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
313 error (EXIT_FAILURE, errno, _("write error"));
317 close_fd (int fd, const char *filename)
319 if (fd != -1 && fd != STDIN_FILENO && close (fd))
321 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
326 write_header (const char *pretty_filename)
328 static int first_file = 1;
330 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
334 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
335 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
336 Return the number of bytes read from the file. */
339 dump_remainder (const char *pretty_filename, int fd, off_t n_bytes)
344 off_t n_remaining = n_bytes;
349 long n = MIN (n_remaining, (off_t) BUFSIZ);
350 bytes_read = safe_read (fd, buffer, n);
353 xwrite (STDOUT_FILENO, buffer, bytes_read);
354 n_remaining -= bytes_read;
355 n_written += bytes_read;
357 if (bytes_read == -1)
358 error (EXIT_FAILURE, errno, "%s", pretty_filename);
363 /* Print the last N_LINES lines from the end of file FD.
364 Go backward through the file, reading `BUFSIZ' bytes at a time (except
365 probably the first), until we hit the start of the file or have
366 read NUMBER newlines.
367 FILE_LENGTH is the length of the file (one more than the offset of the
368 last byte of the file).
369 Return 0 if successful, 1 if an error occurred. */
372 file_lines (const char *pretty_filename, int fd, long int n_lines,
377 int i; /* Index into `buffer' for scanning. */
378 off_t pos = file_length;
383 /* Set `bytes_read' to the size of the last, probably partial, buffer;
384 0 < `bytes_read' <= `BUFSIZ'. */
385 bytes_read = pos % BUFSIZ;
388 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
389 reads will be on block boundaries, which might increase efficiency. */
391 /* FIXME: check lseek return value */
392 lseek (fd, pos, SEEK_SET);
393 bytes_read = safe_read (fd, buffer, bytes_read);
394 if (bytes_read == -1)
396 error (0, errno, "%s", pretty_filename);
400 /* Count the incomplete line on files that don't end with a newline. */
401 if (bytes_read && buffer[bytes_read - 1] != '\n')
406 /* Scan backward, counting the newlines in this bufferfull. */
407 for (i = bytes_read - 1; i >= 0; i--)
409 /* Have we counted the requested number of newlines yet? */
410 if (buffer[i] == '\n' && n_lines-- == 0)
412 /* If this newline wasn't the last character in the buffer,
413 print the text after it. */
414 if (i != bytes_read - 1)
415 xwrite (STDOUT_FILENO, &buffer[i + 1], bytes_read - (i + 1));
416 dump_remainder (pretty_filename, fd,
417 file_length - (pos + bytes_read));
421 /* Not enough newlines in that bufferfull. */
424 /* Not enough lines in the file; print the entire file. */
425 /* FIXME: check lseek return value */
426 lseek (fd, (off_t) 0, SEEK_SET);
427 dump_remainder (pretty_filename, fd, file_length);
431 /* FIXME: check lseek return value */
432 lseek (fd, pos, SEEK_SET);
434 while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0);
436 if (bytes_read == -1)
438 error (0, errno, "%s", pretty_filename);
445 /* Print the last N_LINES lines from the end of the standard input,
446 open for reading as pipe FD.
447 Buffer the text as a linked list of LBUFFERs, adding them as needed.
448 Return 0 if successful, 1 if an error occured. */
451 pipe_lines (const char *pretty_filename, int fd, long int n_lines)
457 struct linebuffer *next;
459 typedef struct linebuffer LBUFFER;
460 LBUFFER *first, *last, *tmp;
461 int i; /* Index into buffers. */
462 int total_lines = 0; /* Total number of newlines in all buffers. */
464 int nbytes; /* Size of most recent read */
466 first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
467 first->nbytes = first->nlines = 0;
469 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
471 /* Input is always read into a fresh buffer. */
472 while ((nbytes = tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
477 /* Count the number of newlines just read. */
478 for (i = 0; i < tmp->nbytes; i++)
479 if (tmp->buffer[i] == '\n')
481 total_lines += tmp->nlines;
483 /* If there is enough room in the last buffer read, just append the new
484 one to it. This is because when reading from a pipe, `nbytes' can
485 often be very small. */
486 if (tmp->nbytes + last->nbytes < BUFSIZ)
488 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
489 last->nbytes += tmp->nbytes;
490 last->nlines += tmp->nlines;
494 /* If there's not enough room, link the new buffer onto the end of
495 the list, then either free up the oldest buffer for the next
496 read if that would leave enough lines, or else malloc a new one.
497 Some compaction mechanism is possible but probably not
499 last = last->next = tmp;
500 if (total_lines - first->nlines > n_lines)
503 total_lines -= first->nlines;
507 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
515 error (0, errno, "%s", pretty_filename);
520 /* If the file is empty, then bail out. */
521 if (last->nbytes == 0)
524 /* This prevents a core dump when the pipe contains no newlines. */
528 /* Count the incomplete line on files that don't end with a newline. */
529 if (last->buffer[last->nbytes - 1] != '\n')
535 /* Run through the list, printing lines. First, skip over unneeded
537 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
538 total_lines -= tmp->nlines;
540 /* Find the correct beginning, then print the rest of the file. */
541 if (total_lines > n_lines)
545 /* Skip `total_lines' - `n_lines' newlines. We made sure that
546 `total_lines' - `n_lines' <= `tmp->nlines'. */
548 for (i = total_lines - n_lines; i; --i)
549 while (*cp++ != '\n')
551 i = cp - tmp->buffer;
555 xwrite (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
557 for (tmp = tmp->next; tmp; tmp = tmp->next)
558 xwrite (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
564 free ((char *) first);
570 /* Print the last N_BYTES characters from the end of pipe FD.
571 This is a stripped down version of pipe_lines.
572 Return 0 if successful, 1 if an error occurred. */
575 pipe_bytes (const char *pretty_filename, int fd, off_t n_bytes)
581 struct charbuffer *next;
583 typedef struct charbuffer CBUFFER;
584 CBUFFER *first, *last, *tmp;
585 int i; /* Index into buffers. */
586 int total_bytes = 0; /* Total characters in all buffers. */
589 first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
592 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
594 /* Input is always read into a fresh buffer. */
595 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
599 total_bytes += tmp->nbytes;
600 /* If there is enough room in the last buffer read, just append the new
601 one to it. This is because when reading from a pipe, `nbytes' can
602 often be very small. */
603 if (tmp->nbytes + last->nbytes < BUFSIZ)
605 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
606 last->nbytes += tmp->nbytes;
610 /* If there's not enough room, link the new buffer onto the end of
611 the list, then either free up the oldest buffer for the next
612 read if that would leave enough characters, or else malloc a new
613 one. Some compaction mechanism is possible but probably not
615 last = last->next = tmp;
616 if (total_bytes - first->nbytes > n_bytes)
619 total_bytes -= first->nbytes;
624 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
628 if (tmp->nbytes == -1)
630 error (0, errno, "%s", pretty_filename);
638 /* Run through the list, printing characters. First, skip over unneeded
640 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
641 total_bytes -= tmp->nbytes;
643 /* Find the correct beginning, then print the rest of the file.
644 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
645 if (total_bytes > n_bytes)
646 i = total_bytes - n_bytes;
649 xwrite (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
651 for (tmp = tmp->next; tmp; tmp = tmp->next)
652 xwrite (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
658 free ((char *) first);
664 /* Skip N_BYTES characters from the start of pipe FD, and print
665 any extra characters that were read beyond that.
666 Return 1 on error, 0 if ok. */
669 start_bytes (const char *pretty_filename, int fd, off_t n_bytes)
674 while (n_bytes > 0 && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
675 n_bytes -= bytes_read;
676 if (bytes_read == -1)
678 error (0, errno, "%s", pretty_filename);
681 else if (n_bytes < 0)
682 xwrite (STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes);
686 /* Skip N_LINES lines at the start of file or pipe FD, and print
687 any extra characters that were read beyond that.
688 Return 1 on error, 0 if ok. */
691 start_lines (const char *pretty_filename, int fd, long int n_lines)
695 int bytes_to_skip = 0;
697 while (n_lines && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
700 while (bytes_to_skip < bytes_read)
701 if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0)
704 if (bytes_read == -1)
706 error (0, errno, "%s", pretty_filename);
709 else if (bytes_to_skip < bytes_read)
711 xwrite (STDOUT_FILENO, &buffer[bytes_to_skip],
712 bytes_read - bytes_to_skip);
717 /* FIXME: describe */
720 recheck (struct File_spec *f)
722 /* open/fstat the file and announce if dev/ino have changed */
723 struct stat new_stats;
726 int is_stdin = (STREQ (f->name, "-"));
727 int was_tailable = f->tailable;
728 int prev_errnum = f->errnum;
731 assert (valid_file_spec (f));
733 fd = (is_stdin ? STDIN_FILENO : open (f->name, O_RDONLY));
735 /* If the open fails because the file doesn't exist,
736 then mark the file as not tailable. */
737 f->tailable = !(reopen_inaccessible_files && fd == -1);
739 if (fd == -1 || fstat (fd, &new_stats) < 0)
747 /* FIXME-maybe: detect the case in which the file first becomes
748 unreadable (perms), and later becomes readable again and can
749 be seen to be the same file (dev/ino). Otherwise, tail prints
750 the entire contents of the file when it becomes readable. */
751 error (0, f->errnum, _("`%s' has become inaccessible"),
756 /* say nothing... it's still not tailable */
759 else if (prev_errnum != errno)
761 error (0, errno, "%s", pretty_name (f));
764 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
768 error (0, 0, _("`%s' has been replaced with an untailable file;\
769 giving up on this name"),
781 close_fd (fd, pretty_name (f));
782 close_fd (f->fd, pretty_name (f));
785 else if (prev_errnum && prev_errnum != ENOENT)
788 assert (f->fd == -1);
789 error (0, 0, _("`%s' has become accessible"), pretty_name (f));
791 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
797 _("`%s' has appeared; following end of new file"),
802 /* Close the old one. */
803 close_fd (f->fd, pretty_name (f));
805 /* File has been replaced (e.g., via log rotation) --
808 _("`%s' has been replaced; following end of new file"),
816 /* This happens when one iteration finds the file missing,
817 then the preceding <dev,inode> pair is reused as the
818 file is recreated. */
823 close_fd (fd, pretty_name (f));
829 /* Record new file info in f. */
831 f->size = 0; /* Start at the beginning of the file... */
832 f->dev = new_stats.st_dev;
833 f->ino = new_stats.st_ino;
834 f->n_unchanged_stats = 0;
835 f->n_consecutive_size_changes = 0;
837 /* FIXME: check lseek return value */
838 lseek (f->fd, f->size, SEEK_SET);
842 /* FIXME: describe */
845 n_live_files (const struct File_spec *f, int n_files)
848 unsigned int n_live = 0;
850 for (i = 0; i < n_files; i++)
858 /* Tail NFILES files forever, or until killed.
859 The pertinent information for each file is stored in an entry of F.
860 Loop over each of them, doing an fstat to see if they have changed size,
861 and an occasional open/fstat to see if any dev/ino pair has changed.
862 If none of them have changed size in one iteration, sleep for a
863 while and try again. Continue until the user interrupts us. */
866 tail_forever (struct File_spec *f, int nfiles)
869 int writer_is_dead = 0;
879 for (i = 0; i < nfiles; i++)
892 if (fstat (f[i].fd, &stats) < 0)
896 error (0, errno, "%s", pretty_name (&f[i]));
900 if (stats.st_size == f[i].size)
902 f[i].n_consecutive_size_changes = 0;
903 if (++f[i].n_unchanged_stats > max_n_unchanged_stats_between_opens
904 && follow_mode == Follow_name)
907 f[i].n_unchanged_stats = 0;
913 ++f[i].n_consecutive_size_changes;
915 /* Ensure that a file that's unlinked or moved aside, yet always
916 growing will be recognized as having been renamed. */
917 if (follow_mode == Follow_name
918 && (f[i].n_consecutive_size_changes
919 > max_n_consecutive_size_changes_between_opens))
921 f[i].n_consecutive_size_changes = 0;
926 /* This file has changed size. Print out what we can, and
927 then keep looping. */
932 f[i].n_unchanged_stats = 0;
934 if (stats.st_size < f[i].size)
936 error (0, 0, _("%s: file truncated"), pretty_name (&f[i]));
938 /* FIXME: check lseek return value */
939 lseek (f[i].fd, stats.st_size, SEEK_SET);
940 f[i].size = stats.st_size;
947 write_header (pretty_name (&f[i]));
950 f[i].size += dump_remainder (pretty_name (&f[i]), f[i].fd,
954 if (n_live_files (f, nfiles) == 0 && ! reopen_inaccessible_files)
956 error (0, 0, _("no files remaining"));
960 /* If none of the files changed size, sleep. */
965 sleep (sleep_interval);
967 /* Once the writer is dead, read the files once more to
968 avoid a race condition. */
969 writer_is_dead = (pid != 0
970 && kill (pid, 0) != 0
971 /* Handle the case in which you cannot send a
972 signal to the writer, so kill fails and sets
979 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
980 Return 0 if successful, 1 if an error occurred. */
983 tail_bytes (const char *pretty_filename, int fd, off_t n_bytes)
987 /* We need binary input, since `tail' relies on `lseek' and byte counts,
988 while binary output will preserve the style (Unix/DOS) of text file. */
989 SET_BINARY2 (fd, STDOUT_FILENO);
991 if (fstat (fd, &stats))
993 error (0, errno, "%s", pretty_filename);
999 if (S_ISREG (stats.st_mode))
1001 /* FIXME: check lseek return value */
1002 lseek (fd, n_bytes, SEEK_CUR);
1004 else if (start_bytes (pretty_filename, fd, n_bytes))
1008 dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1012 if (S_ISREG (stats.st_mode))
1014 off_t current_pos, end_pos;
1015 size_t bytes_remaining;
1017 if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1
1018 && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1)
1021 /* Be careful here. The current position may actually be
1022 beyond the end of the file. */
1023 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
1027 error (0, errno, "%s", pretty_filename);
1031 if (bytes_remaining <= n_bytes)
1033 /* From the current position to end of file, there are no
1034 more bytes than have been requested. So reposition the
1035 file pointer to the incoming current position and print
1036 everything after that. */
1037 /* FIXME: check lseek return value */
1038 lseek (fd, current_pos, SEEK_SET);
1042 /* There are more bytes remaining than were requested.
1044 /* FIXME: check lseek return value */
1045 lseek (fd, -n_bytes, SEEK_END);
1047 dump_remainder (pretty_filename, fd, n_bytes);
1050 return pipe_bytes (pretty_filename, fd, n_bytes);
1055 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1056 Return 0 if successful, 1 if an error occurred. */
1059 tail_lines (const char *pretty_filename, int fd, long int n_lines)
1064 /* We need binary input, since `tail' relies on `lseek' and byte counts,
1065 while binary output will preserve the style (Unix/DOS) of text file. */
1066 SET_BINARY2 (fd, STDOUT_FILENO);
1068 if (fstat (fd, &stats))
1070 error (0, errno, "%s", pretty_filename);
1076 if (start_lines (pretty_filename, fd, n_lines))
1078 dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1082 /* Use file_lines only if FD refers to a regular file with
1083 its file pointer positioned at beginning of file. */
1084 /* FIXME: adding the lseek conjunct is a kludge.
1085 Once there's a reasonable test suite, fix the true culprit:
1086 file_lines. file_lines shouldn't presume that the input
1087 file pointer is initially positioned to beginning of file. */
1088 if (S_ISREG (stats.st_mode)
1089 && lseek (fd, (off_t) 0, SEEK_CUR) == (off_t) 0)
1091 length = lseek (fd, (off_t) 0, SEEK_END);
1092 if (length != 0 && file_lines (pretty_filename, fd, n_lines, length))
1096 return pipe_lines (pretty_filename, fd, n_lines);
1101 /* Display the last N_UNITS units of file FILENAME, open for reading
1103 Return 0 if successful, 1 if an error occurred. */
1106 tail (const char *pretty_filename, int fd, off_t n_units)
1109 return tail_lines (pretty_filename, fd, (long) n_units);
1111 return tail_bytes (pretty_filename, fd, n_units);
1114 /* Display the last N_UNITS units of the file described by F.
1115 Return 0 if successful, 1 if an error occurred. */
1118 tail_file (struct File_spec *f, off_t n_units)
1123 int is_stdin = (STREQ (f->name, "-"));
1127 have_read_stdin = 1;
1132 fd = open (f->name, O_RDONLY);
1135 f->tailable = !(reopen_inaccessible_files && fd == -1);
1147 error (0, errno, "%s", pretty_name (f));
1153 write_header (pretty_name (f));
1154 errors = tail (pretty_name (f), fd, n_units);
1158 /* FIXME: duplicate code */
1159 if (fstat (fd, &stats) < 0)
1163 error (0, errno, "%s", pretty_name (f));
1165 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1167 error (0, 0, _("%s: cannot follow end of this type of file;\
1168 giving up on this name"),
1177 close_fd (fd, pretty_name (f));
1183 f->size = stats.st_size;
1184 f->dev = stats.st_dev;
1185 f->ino = stats.st_ino;
1186 f->n_unchanged_stats = 0;
1187 f->n_consecutive_size_changes = 0;
1193 if (!is_stdin && close (fd))
1195 error (0, errno, "%s", pretty_name (f));
1204 /* If the command line arguments are of the obsolescent form and the
1205 option string is well-formed, set *FAIL to zero, set *N_UNITS, the
1206 globals COUNT_LINES, FOREVER, and FROM_START, and return non-zero.
1207 Otherwise, if the command line arguments appear to be of the
1208 obsolescent form but the option string is malformed, set *FAIL to
1209 non-zero, don't modify any other parameter or global variable, and
1210 return non-zero. Otherwise, return zero and don't modify any parameter
1211 or global variable. */
1214 parse_obsolescent_option (int argc, const char *const *argv,
1215 off_t *n_units, int *fail)
1217 const char *p = argv[1];
1218 const char *n_string = NULL;
1219 const char *n_string_end;
1225 /* With the obsolescent form, there is one option string and
1226 (technically) at most one file argument. But we allow two or more
1231 /* If P starts with `+', `-N' (where N is a digit), or `-l',
1232 then it is obsolescent. Return zero otherwise. */
1233 if ( ! (p[0] == '+' || (p[0] == '-' && (p[1] == 'l' || ISDIGIT (p[1])))) )
1251 while (ISDIGIT (*p));
1275 /* If (argv[1] begins with a `+' or if it begins with `-' followed
1276 by a digit), but has an invalid suffix character, give a diagnostic
1277 and indicate to caller that this *is* of the obsolescent form,
1278 but that it's an invalid option. */
1279 if (t_from_start || n_string)
1282 _("%c: invalid suffix character in obsolescent option" ), *p);
1287 /* Otherwise, it might be a valid non-obsolescent option like -n. */
1292 if (n_string == NULL)
1293 *n_units = DEFAULT_N_LINES;
1297 unsigned long int tmp_ulong;
1299 s_err = xstrtoul (n_string, &end, 10, &tmp_ulong, NULL);
1300 if (s_err == LONGINT_OK && tmp_ulong <= OFF_T_MAX)
1301 *n_units = (off_t) tmp_ulong;
1304 /* Extract a NUL-terminated string for the error message. */
1305 size_t len = n_string_end - n_string;
1306 char *n_string_tmp = xmalloc (len + 1);
1308 strncpy (n_string_tmp, n_string, len);
1309 n_string_tmp[len] = '\0';
1312 _("%s: %s is so large that it is not representable"),
1313 n_string_tmp, (count_lines
1314 ? _("number of lines")
1315 : _("number of bytes")));
1316 free (n_string_tmp);
1325 int posix_pedantic = (getenv ("POSIXLY_CORRECT") != NULL);
1327 /* When POSIXLY_CORRECT is set, enforce the `at most one
1328 file argument' requirement. */
1332 too many arguments; When using tail's obsolescent option syntax (%s)\n\
1333 there may be no more than one file argument. Use the equivalent -n or -c\n\
1334 option instead."), argv[1]);
1339 #if DISABLED /* FIXME: enable or remove this warning. */
1341 Warning: it is not portable to use two or more file arguments with\n\
1342 tail's obsolescent option syntax (%s). Use the equivalent -n or -c\n\
1343 option instead."), argv[1]);
1348 from_start = t_from_start;
1349 count_lines = t_count_lines;
1350 forever = t_forever;
1357 parse_options (int argc, char **argv,
1358 off_t *n_units, enum header_mode *header_mode)
1363 forever = from_start = print_headers = 0;
1365 while ((c = getopt_long (argc, argv, "c:n:fqs:v", long_options, NULL))
1375 count_lines = (c == 'n');
1378 else if (*optarg == '-')
1384 s_err = xstrtoumax (optarg, NULL, 10, &n, "bkm");
1385 if (s_err == LONGINT_INVALID)
1387 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1389 ? _("invalid number of lines")
1390 : _("invalid number of bytes")));
1393 if (s_err != LONGINT_OK)
1394 error (EXIT_FAILURE, 0,
1395 _("%s: is so large that it is not representable"), optarg);
1398 error (EXIT_FAILURE, 0,
1399 _("%s is larger than the maximum file size on this system"),
1401 *n_units = (off_t) n;
1406 case LONG_FOLLOW_OPTION:
1409 follow_mode = DEFAULT_FOLLOW_MODE;
1411 follow_mode = XARGMATCH ("--follow", optarg,
1412 follow_mode_string, follow_mode_map);
1416 reopen_inaccessible_files = 1;
1419 case MAX_UNCHANGED_STATS_OPTION:
1420 /* --max-unchanged-stats=N */
1421 if (xstrtoul (optarg, NULL, 10,
1422 &max_n_unchanged_stats_between_opens, "") != LONGINT_OK)
1424 error (EXIT_FAILURE, 0,
1425 _("%s: invalid maximum number of unchanged stats between opens"),
1430 case MAX_CONSECUTIVE_SIZE_CHANGES_OPTION:
1431 /* --max-consecutive-size-changes=N */
1432 if (xstrtoul (optarg, NULL, 10,
1433 &max_n_consecutive_size_changes_between_opens, "")
1436 error (EXIT_FAILURE, 0,
1437 _("%s: invalid maximum number of consecutive size changes"),
1445 unsigned long int tmp_ulong;
1446 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1447 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1449 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1456 *header_mode = never;
1462 unsigned long int tmp_ulong;
1463 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1464 if (s_err != LONGINT_OK || tmp_ulong > UINT_MAX)
1466 error (EXIT_FAILURE, 0,
1467 _("%s: invalid number of seconds"), optarg);
1469 sleep_interval = tmp_ulong;
1474 *header_mode = always;
1477 case_GETOPT_HELP_CHAR;
1479 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1486 if (reopen_inaccessible_files && follow_mode != Follow_name)
1487 error (0, 0, _("warning: --retry is useful only when following by name"));
1489 if (pid && !forever)
1491 _("warning: PID ignored; --pid=PID is useful only when following"));
1492 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
1494 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1500 main (int argc, char **argv)
1502 enum header_mode header_mode = multiple_files;
1503 int exit_status = 0;
1504 /* If from_start, the number of items to skip before printing; otherwise,
1505 the number of items at the end of the file to print. Although the type
1506 is signed, the value is never negative. */
1507 off_t n_units = DEFAULT_N_LINES;
1510 struct File_spec *F;
1513 program_name = argv[0];
1514 setlocale (LC_ALL, "");
1515 bindtextdomain (PACKAGE, LOCALEDIR);
1516 textdomain (PACKAGE);
1518 atexit (close_stdout);
1520 have_read_stdin = 0;
1523 int found_obsolescent;
1525 found_obsolescent = parse_obsolescent_option (argc,
1526 (const char *const *) argv,
1528 if (found_obsolescent)
1531 exit (EXIT_FAILURE);
1536 parse_options (argc, argv, &n_units, &header_mode);
1540 /* To start printing with item N_UNITS from the start of the file, skip
1541 N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix
1542 compatibility it's treated the same as `tail +1'. */
1549 n_files = argc - optind;
1550 file = argv + optind;
1554 static char *dummy_stdin = "-";
1556 file = &dummy_stdin;
1559 F = (struct File_spec *) xmalloc (n_files * sizeof (F[0]));
1560 for (i = 0; i < n_files; i++)
1561 F[i].name = file[i];
1563 if (header_mode == always
1564 || (header_mode == multiple_files && n_files > 1))
1567 for (i = 0; i < n_files; i++)
1568 exit_status |= tail_file (&F[i], n_units);
1572 /* This fflush appears to be required only on Solaris2.7. */
1573 if (fflush (stdout) < 0)
1574 error (EXIT_FAILURE, errno, _("write error"));
1576 SETVBUF (stdout, NULL, _IONBF, 0);
1577 tail_forever (F, n_files);
1580 if (have_read_stdin && close (0) < 0)
1581 error (EXIT_FAILURE, errno, "-");
1582 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);