*** empty log message ***
[coreutils.git] / src / tail.c
blob0c547507dc2b8a887348ffd9c212e78616149e1e
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)
7 any later version.
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
20 of lines.
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>. */
26 #include <config.h>
28 #include <stdio.h>
29 #include <assert.h>
30 #include <getopt.h>
31 #include <sys/types.h>
32 #include <signal.h>
34 #include "system.h"
35 #include "closeout.h"
36 #include "argmatch.h"
37 #include "error.h"
38 #include "safe-read.h"
39 #include "xstrtol.h"
41 /* The official name of this program (e.g., no `g' prefix). */
42 #define PROGRAM_NAME "tail"
44 #define AUTHORS \
45 "Paul Rubin, David MacKenzie, Ian Lance Taylor, and Jim Meyering"
47 #ifndef ENOSYS
48 /* Some systems don't have ENOSYS -- this should be a big enough
49 value that no valid errno value will match it. */
50 # define ENOSYS 99999
51 #endif
53 /* Number of items to tail. */
54 #define DEFAULT_N_LINES 10
56 /* Size of atomic reads. */
57 #ifndef BUFSIZ
58 # define BUFSIZ (512 * 8)
59 #endif
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
67 enum Follow_mode
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. */
72 Follow_name = 1,
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 /* 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,
94 struct File_spec
96 /* The actual file name, or "-" for stdin. */
97 char *name;
99 /* File descriptor on which the file is open; -1 if it's not open. */
100 int fd;
102 /* The size of the file the last time we checked. */
103 off_t size;
105 /* The device and inode of the file the last time we checked. */
106 dev_t dev;
107 ino_t ino;
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. */
112 int ignore;
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. */
122 int tailable;
124 /* The value of errno seen last time we checked this file. */
125 int errnum;
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. */
142 static int forever;
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. */
151 enum header_mode
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. */
176 char *program_name;
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. */
186 static pid_t pid;
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. */
193 enum
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,
202 PID_OPTION,
203 LONG_FOLLOW_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},
225 {NULL, 0, NULL, 0}
228 void
229 usage (int status)
231 if (status != 0)
232 fprintf (stderr, _("Try `%s --help' for more information.\n"),
233 program_name);
234 else
236 printf (_("\
237 Usage: %s [OPTION]... [FILE]...\n\
239 program_name);
240 printf (_("\
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\
251 equivalent\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
270 printf (_("\
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.\n\
279 With --follow (-f), tail defaults to following the file descriptor, which\n\
280 means that even if a tail'ed file is renamed, tail will continue to track\n\
281 its end. This default behavior is not desirable when you really want to\n\
282 track the actual name of the file, not the file descriptor (e.g., log\n\
283 rotation). Use --follow=name in that case. That causes tail to track the\n\
284 named file by reopening it periodically to see if it has been removed and\n\
285 recreated by some other program.\n\
287 "));
288 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
290 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
293 static int
294 valid_file_spec (struct File_spec const *f)
296 /* Exactly one of the following subexpressions must be true. */
297 return ((f->fd == -1) ^ (f->errnum == 0));
300 static char *
301 pretty_name (struct File_spec const *f)
303 return (STREQ (f->name, "-") ? "standard input" : f->name);
306 static void
307 xwrite (int fd, char *const buffer, size_t n_bytes)
309 assert (fd == STDOUT_FILENO);
310 assert (n_bytes >= 0);
311 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
312 error (EXIT_FAILURE, errno, _("write error"));
315 static void
316 close_fd (int fd, const char *filename)
318 if (fd != -1 && fd != STDIN_FILENO && close (fd))
320 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
324 static void
325 write_header (const char *pretty_filename)
327 static int first_file = 1;
329 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
330 first_file = 0;
333 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
334 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
335 Return the number of bytes read from the file. */
337 static long
338 dump_remainder (const char *pretty_filename, int fd, off_t n_bytes)
340 char buffer[BUFSIZ];
341 int bytes_read;
342 long n_written;
343 off_t n_remaining = n_bytes;
345 n_written = 0;
346 while (1)
348 long n = MIN (n_remaining, (off_t) BUFSIZ);
349 bytes_read = safe_read (fd, buffer, n);
350 if (bytes_read <= 0)
351 break;
352 xwrite (STDOUT_FILENO, buffer, bytes_read);
353 n_remaining -= bytes_read;
354 n_written += bytes_read;
356 if (bytes_read == -1)
357 error (EXIT_FAILURE, errno, "%s", pretty_filename);
359 return n_written;
362 /* Print the last N_LINES lines from the end of file FD.
363 Go backward through the file, reading `BUFSIZ' bytes at a time (except
364 probably the first), until we hit the start of the file or have
365 read NUMBER newlines.
366 FILE_LENGTH is the length of the file (one more than the offset of the
367 last byte of the file).
368 Return 0 if successful, 1 if an error occurred. */
370 static int
371 file_lines (const char *pretty_filename, int fd, long int n_lines,
372 off_t file_length)
374 char buffer[BUFSIZ];
375 int bytes_read;
376 int i; /* Index into `buffer' for scanning. */
377 off_t pos = file_length;
379 if (n_lines == 0)
380 return 0;
382 /* Set `bytes_read' to the size of the last, probably partial, buffer;
383 0 < `bytes_read' <= `BUFSIZ'. */
384 bytes_read = pos % BUFSIZ;
385 if (bytes_read == 0)
386 bytes_read = BUFSIZ;
387 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
388 reads will be on block boundaries, which might increase efficiency. */
389 pos -= bytes_read;
390 /* FIXME: check lseek return value */
391 lseek (fd, pos, SEEK_SET);
392 bytes_read = safe_read (fd, buffer, bytes_read);
393 if (bytes_read == -1)
395 error (0, errno, "%s", pretty_filename);
396 return 1;
399 /* Count the incomplete line on files that don't end with a newline. */
400 if (bytes_read && buffer[bytes_read - 1] != '\n')
401 --n_lines;
405 /* Scan backward, counting the newlines in this bufferfull. */
406 for (i = bytes_read - 1; i >= 0; i--)
408 /* Have we counted the requested number of newlines yet? */
409 if (buffer[i] == '\n' && n_lines-- == 0)
411 /* If this newline wasn't the last character in the buffer,
412 print the text after it. */
413 if (i != bytes_read - 1)
414 xwrite (STDOUT_FILENO, &buffer[i + 1], bytes_read - (i + 1));
415 dump_remainder (pretty_filename, fd,
416 file_length - (pos + bytes_read));
417 return 0;
420 /* Not enough newlines in that bufferfull. */
421 if (pos == 0)
423 /* Not enough lines in the file; print the entire file. */
424 /* FIXME: check lseek return value */
425 lseek (fd, (off_t) 0, SEEK_SET);
426 dump_remainder (pretty_filename, fd, file_length);
427 return 0;
429 pos -= BUFSIZ;
430 /* FIXME: check lseek return value */
431 lseek (fd, pos, SEEK_SET);
433 while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0);
435 if (bytes_read == -1)
437 error (0, errno, "%s", pretty_filename);
438 return 1;
441 return 0;
444 /* Print the last N_LINES lines from the end of the standard input,
445 open for reading as pipe FD.
446 Buffer the text as a linked list of LBUFFERs, adding them as needed.
447 Return 0 if successful, 1 if an error occured. */
449 static int
450 pipe_lines (const char *pretty_filename, int fd, long int n_lines)
452 struct linebuffer
454 int nbytes, nlines;
455 char buffer[BUFSIZ];
456 struct linebuffer *next;
458 typedef struct linebuffer LBUFFER;
459 LBUFFER *first, *last, *tmp;
460 int i; /* Index into buffers. */
461 int total_lines = 0; /* Total number of newlines in all buffers. */
462 int errors = 0;
463 int nbytes; /* Size of most recent read */
465 first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
466 first->nbytes = first->nlines = 0;
467 first->next = NULL;
468 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
470 /* Input is always read into a fresh buffer. */
471 while ((nbytes = tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
473 tmp->nlines = 0;
474 tmp->next = NULL;
476 /* Count the number of newlines just read. */
477 for (i = 0; i < tmp->nbytes; i++)
478 if (tmp->buffer[i] == '\n')
479 ++tmp->nlines;
480 total_lines += tmp->nlines;
482 /* If there is enough room in the last buffer read, just append the new
483 one to it. This is because when reading from a pipe, `nbytes' can
484 often be very small. */
485 if (tmp->nbytes + last->nbytes < BUFSIZ)
487 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
488 last->nbytes += tmp->nbytes;
489 last->nlines += tmp->nlines;
491 else
493 /* If there's not enough room, link the new buffer onto the end of
494 the list, then either free up the oldest buffer for the next
495 read if that would leave enough lines, or else malloc a new one.
496 Some compaction mechanism is possible but probably not
497 worthwhile. */
498 last = last->next = tmp;
499 if (total_lines - first->nlines > n_lines)
501 tmp = first;
502 total_lines -= first->nlines;
503 first = first->next;
505 else
506 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
510 free ((char *) tmp);
512 if (nbytes < 0)
514 error (0, errno, "%s", pretty_filename);
515 errors = 1;
516 goto free_lbuffers;
519 /* If the file is empty, then bail out. */
520 if (last->nbytes == 0)
521 goto free_lbuffers;
523 /* This prevents a core dump when the pipe contains no newlines. */
524 if (n_lines == 0)
525 goto free_lbuffers;
527 /* Count the incomplete line on files that don't end with a newline. */
528 if (last->buffer[last->nbytes - 1] != '\n')
530 ++last->nlines;
531 ++total_lines;
534 /* Run through the list, printing lines. First, skip over unneeded
535 buffers. */
536 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
537 total_lines -= tmp->nlines;
539 /* Find the correct beginning, then print the rest of the file. */
540 if (total_lines > n_lines)
542 const char *cp;
544 /* Skip `total_lines' - `n_lines' newlines. We made sure that
545 `total_lines' - `n_lines' <= `tmp->nlines'. */
546 cp = tmp->buffer;
547 for (i = total_lines - n_lines; i; --i)
548 while (*cp++ != '\n')
549 /* Do nothing. */ ;
550 i = cp - tmp->buffer;
552 else
553 i = 0;
554 xwrite (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
556 for (tmp = tmp->next; tmp; tmp = tmp->next)
557 xwrite (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
559 free_lbuffers:
560 while (first)
562 tmp = first->next;
563 free ((char *) first);
564 first = tmp;
566 return errors;
569 /* Print the last N_BYTES characters from the end of pipe FD.
570 This is a stripped down version of pipe_lines.
571 Return 0 if successful, 1 if an error occurred. */
573 static int
574 pipe_bytes (const char *pretty_filename, int fd, off_t n_bytes)
576 struct charbuffer
578 int nbytes;
579 char buffer[BUFSIZ];
580 struct charbuffer *next;
582 typedef struct charbuffer CBUFFER;
583 CBUFFER *first, *last, *tmp;
584 int i; /* Index into buffers. */
585 int total_bytes = 0; /* Total characters in all buffers. */
586 int errors = 0;
588 first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
589 first->nbytes = 0;
590 first->next = NULL;
591 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
593 /* Input is always read into a fresh buffer. */
594 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
596 tmp->next = NULL;
598 total_bytes += tmp->nbytes;
599 /* If there is enough room in the last buffer read, just append the new
600 one to it. This is because when reading from a pipe, `nbytes' can
601 often be very small. */
602 if (tmp->nbytes + last->nbytes < BUFSIZ)
604 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
605 last->nbytes += tmp->nbytes;
607 else
609 /* If there's not enough room, link the new buffer onto the end of
610 the list, then either free up the oldest buffer for the next
611 read if that would leave enough characters, or else malloc a new
612 one. Some compaction mechanism is possible but probably not
613 worthwhile. */
614 last = last->next = tmp;
615 if (total_bytes - first->nbytes > n_bytes)
617 tmp = first;
618 total_bytes -= first->nbytes;
619 first = first->next;
621 else
623 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
627 if (tmp->nbytes == -1)
629 error (0, errno, "%s", pretty_filename);
630 errors = 1;
631 free ((char *) tmp);
632 goto free_cbuffers;
635 free ((char *) tmp);
637 /* Run through the list, printing characters. First, skip over unneeded
638 buffers. */
639 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
640 total_bytes -= tmp->nbytes;
642 /* Find the correct beginning, then print the rest of the file.
643 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
644 if (total_bytes > n_bytes)
645 i = total_bytes - n_bytes;
646 else
647 i = 0;
648 xwrite (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
650 for (tmp = tmp->next; tmp; tmp = tmp->next)
651 xwrite (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
653 free_cbuffers:
654 while (first)
656 tmp = first->next;
657 free ((char *) first);
658 first = tmp;
660 return errors;
663 /* Skip N_BYTES characters from the start of pipe FD, and print
664 any extra characters that were read beyond that.
665 Return 1 on error, 0 if ok. */
667 static int
668 start_bytes (const char *pretty_filename, int fd, off_t n_bytes)
670 char buffer[BUFSIZ];
671 int bytes_read = 0;
673 while (n_bytes > 0 && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
674 n_bytes -= bytes_read;
675 if (bytes_read == -1)
677 error (0, errno, "%s", pretty_filename);
678 return 1;
680 else if (n_bytes < 0)
681 xwrite (STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes);
682 return 0;
685 /* Skip N_LINES lines at the start of file or pipe FD, and print
686 any extra characters that were read beyond that.
687 Return 1 on error, 0 if ok. */
689 static int
690 start_lines (const char *pretty_filename, int fd, long int n_lines)
692 char buffer[BUFSIZ];
693 int bytes_read = 0;
694 int bytes_to_skip = 0;
696 while (n_lines && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
698 bytes_to_skip = 0;
699 while (bytes_to_skip < bytes_read)
700 if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0)
701 break;
703 if (bytes_read == -1)
705 error (0, errno, "%s", pretty_filename);
706 return 1;
708 else if (bytes_to_skip < bytes_read)
710 xwrite (STDOUT_FILENO, &buffer[bytes_to_skip],
711 bytes_read - bytes_to_skip);
713 return 0;
716 /* FIXME: describe */
718 static void
719 recheck (struct File_spec *f)
721 /* open/fstat the file and announce if dev/ino have changed */
722 struct stat new_stats;
723 int fd;
724 int fail = 0;
725 int is_stdin = (STREQ (f->name, "-"));
726 int was_tailable = f->tailable;
727 int prev_errnum = f->errnum;
728 int new_file;
730 assert (valid_file_spec (f));
732 fd = (is_stdin ? STDIN_FILENO : open (f->name, O_RDONLY));
734 /* If the open fails because the file doesn't exist,
735 then mark the file as not tailable. */
736 f->tailable = !(reopen_inaccessible_files && fd == -1);
738 if (fd == -1 || fstat (fd, &new_stats) < 0)
740 fail = 1;
741 f->errnum = errno;
742 if (!f->tailable)
744 if (was_tailable)
746 /* FIXME-maybe: detect the case in which the file first becomes
747 unreadable (perms), and later becomes readable again and can
748 be seen to be the same file (dev/ino). Otherwise, tail prints
749 the entire contents of the file when it becomes readable. */
750 error (0, f->errnum, _("`%s' has become inaccessible"),
751 pretty_name (f));
753 else
755 /* say nothing... it's still not tailable */
758 else if (prev_errnum != errno)
760 error (0, errno, "%s", pretty_name (f));
763 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
765 fail = 1;
766 f->errnum = -1;
767 error (0, 0, _("`%s' has been replaced with an untailable file;\
768 giving up on this name"),
769 pretty_name (f));
770 f->ignore = 1;
772 else
774 f->errnum = 0;
777 new_file = 0;
778 if (fail)
780 close_fd (fd, pretty_name (f));
781 close_fd (f->fd, pretty_name (f));
782 f->fd = -1;
784 else if (prev_errnum && prev_errnum != ENOENT)
786 new_file = 1;
787 assert (f->fd == -1);
788 error (0, 0, _("`%s' has become accessible"), pretty_name (f));
790 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
792 new_file = 1;
793 if (f->fd == -1)
795 error (0, 0,
796 _("`%s' has appeared; following end of new file"),
797 pretty_name (f));
799 else
801 /* Close the old one. */
802 close_fd (f->fd, pretty_name (f));
804 /* File has been replaced (e.g., via log rotation) --
805 tail the new one. */
806 error (0, 0,
807 _("`%s' has been replaced; following end of new file"),
808 pretty_name (f));
811 else
813 if (f->fd == -1)
815 /* This happens when one iteration finds the file missing,
816 then the preceding <dev,inode> pair is reused as the
817 file is recreated. */
818 new_file = 1;
820 else
822 close_fd (fd, pretty_name (f));
826 if (new_file)
828 /* Record new file info in f. */
829 f->fd = fd;
830 f->size = 0; /* Start at the beginning of the file... */
831 f->dev = new_stats.st_dev;
832 f->ino = new_stats.st_ino;
833 f->n_unchanged_stats = 0;
834 f->n_consecutive_size_changes = 0;
835 f->ignore = 0;
836 /* FIXME: check lseek return value */
837 lseek (f->fd, f->size, SEEK_SET);
841 /* FIXME: describe */
843 static unsigned int
844 n_live_files (const struct File_spec *f, int n_files)
846 int i;
847 unsigned int n_live = 0;
849 for (i = 0; i < n_files; i++)
851 if (f[i].fd >= 0)
852 ++n_live;
854 return n_live;
857 /* Tail NFILES files forever, or until killed.
858 The pertinent information for each file is stored in an entry of F.
859 Loop over each of them, doing an fstat to see if they have changed size,
860 and an occasional open/fstat to see if any dev/ino pair has changed.
861 If none of them have changed size in one iteration, sleep for a
862 while and try again. Continue until the user interrupts us. */
864 static void
865 tail_forever (struct File_spec *f, int nfiles)
867 int last;
868 int writer_is_dead = 0;
870 last = nfiles - 1;
872 while (1)
874 int i;
875 int any_changed;
877 any_changed = 0;
878 for (i = 0; i < nfiles; i++)
880 struct stat stats;
882 if (f[i].ignore)
883 continue;
885 if (f[i].fd < 0)
887 recheck (&f[i]);
888 continue;
891 if (fstat (f[i].fd, &stats) < 0)
893 f[i].fd = -1;
894 f[i].errnum = errno;
895 error (0, errno, "%s", pretty_name (&f[i]));
896 continue;
899 if (stats.st_size == f[i].size)
901 f[i].n_consecutive_size_changes = 0;
902 if (++f[i].n_unchanged_stats > max_n_unchanged_stats_between_opens
903 && follow_mode == Follow_name)
905 recheck (&f[i]);
906 f[i].n_unchanged_stats = 0;
908 continue;
911 /* Size changed. */
912 ++f[i].n_consecutive_size_changes;
914 /* Ensure that a file that's unlinked or moved aside, yet always
915 growing will be recognized as having been renamed. */
916 if (follow_mode == Follow_name
917 && (f[i].n_consecutive_size_changes
918 > max_n_consecutive_size_changes_between_opens))
920 f[i].n_consecutive_size_changes = 0;
921 recheck (&f[i]);
922 continue;
925 /* This file has changed size. Print out what we can, and
926 then keep looping. */
928 any_changed = 1;
930 /* reset counter */
931 f[i].n_unchanged_stats = 0;
933 if (stats.st_size < f[i].size)
935 error (0, 0, _("%s: file truncated"), pretty_name (&f[i]));
936 last = i;
937 /* FIXME: check lseek return value */
938 lseek (f[i].fd, stats.st_size, SEEK_SET);
939 f[i].size = stats.st_size;
940 continue;
943 if (i != last)
945 if (print_headers)
946 write_header (pretty_name (&f[i]));
947 last = i;
949 f[i].size += dump_remainder (pretty_name (&f[i]), f[i].fd,
950 COPY_TO_EOF);
953 if (n_live_files (f, nfiles) == 0 && ! reopen_inaccessible_files)
955 error (0, 0, _("no files remaining"));
956 break;
959 /* If none of the files changed size, sleep. */
960 if (!any_changed)
962 if (writer_is_dead)
963 break;
964 sleep (sleep_interval);
966 /* Once the writer is dead, read the files once more to
967 avoid a race condition. */
968 writer_is_dead = (pid != 0
969 && kill (pid, 0) != 0
970 /* Handle the case in which you cannot send a
971 signal to the writer, so kill fails and sets
972 errno to EPERM. */
973 && errno != EPERM);
978 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
979 Return 0 if successful, 1 if an error occurred. */
981 static int
982 tail_bytes (const char *pretty_filename, int fd, off_t n_bytes)
984 struct stat stats;
986 /* We need binary input, since `tail' relies on `lseek' and byte counts,
987 while binary output will preserve the style (Unix/DOS) of text file. */
988 SET_BINARY2 (fd, STDOUT_FILENO);
990 if (fstat (fd, &stats))
992 error (0, errno, "%s", pretty_filename);
993 return 1;
996 if (from_start)
998 if (S_ISREG (stats.st_mode))
1000 /* FIXME: check lseek return value */
1001 lseek (fd, n_bytes, SEEK_CUR);
1003 else if (start_bytes (pretty_filename, fd, n_bytes))
1005 return 1;
1007 dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1009 else
1011 if (S_ISREG (stats.st_mode))
1013 off_t current_pos, end_pos;
1014 size_t bytes_remaining;
1016 if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1
1017 && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1)
1019 off_t diff;
1020 /* Be careful here. The current position may actually be
1021 beyond the end of the file. */
1022 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
1024 else
1026 error (0, errno, "%s", pretty_filename);
1027 return 1;
1030 if (bytes_remaining <= n_bytes)
1032 /* From the current position to end of file, there are no
1033 more bytes than have been requested. So reposition the
1034 file pointer to the incoming current position and print
1035 everything after that. */
1036 /* FIXME: check lseek return value */
1037 lseek (fd, current_pos, SEEK_SET);
1039 else
1041 /* There are more bytes remaining than were requested.
1042 Back up. */
1043 /* FIXME: check lseek return value */
1044 lseek (fd, -n_bytes, SEEK_END);
1046 dump_remainder (pretty_filename, fd, n_bytes);
1048 else
1049 return pipe_bytes (pretty_filename, fd, n_bytes);
1051 return 0;
1054 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1055 Return 0 if successful, 1 if an error occurred. */
1057 static int
1058 tail_lines (const char *pretty_filename, int fd, long int n_lines)
1060 struct stat stats;
1061 off_t length;
1063 /* We need binary input, since `tail' relies on `lseek' and byte counts,
1064 while binary output will preserve the style (Unix/DOS) of text file. */
1065 SET_BINARY2 (fd, STDOUT_FILENO);
1067 if (fstat (fd, &stats))
1069 error (0, errno, "%s", pretty_filename);
1070 return 1;
1073 if (from_start)
1075 if (start_lines (pretty_filename, fd, n_lines))
1076 return 1;
1077 dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1079 else
1081 /* Use file_lines only if FD refers to a regular file with
1082 its file pointer positioned at beginning of file. */
1083 /* FIXME: adding the lseek conjunct is a kludge.
1084 Once there's a reasonable test suite, fix the true culprit:
1085 file_lines. file_lines shouldn't presume that the input
1086 file pointer is initially positioned to beginning of file. */
1087 if (S_ISREG (stats.st_mode)
1088 && lseek (fd, (off_t) 0, SEEK_CUR) == (off_t) 0)
1090 length = lseek (fd, (off_t) 0, SEEK_END);
1091 if (length != 0 && file_lines (pretty_filename, fd, n_lines, length))
1092 return 1;
1094 else
1095 return pipe_lines (pretty_filename, fd, n_lines);
1097 return 0;
1100 /* Display the last N_UNITS units of file FILENAME, open for reading
1101 in FD.
1102 Return 0 if successful, 1 if an error occurred. */
1104 static int
1105 tail (const char *pretty_filename, int fd, off_t n_units)
1107 if (count_lines)
1108 return tail_lines (pretty_filename, fd, (long) n_units);
1109 else
1110 return tail_bytes (pretty_filename, fd, n_units);
1113 /* Display the last N_UNITS units of the file described by F.
1114 Return 0 if successful, 1 if an error occurred. */
1116 static int
1117 tail_file (struct File_spec *f, off_t n_units)
1119 int fd, errors;
1120 struct stat stats;
1122 int is_stdin = (STREQ (f->name, "-"));
1124 if (is_stdin)
1126 have_read_stdin = 1;
1127 fd = STDIN_FILENO;
1129 else
1131 fd = open (f->name, O_RDONLY);
1134 f->tailable = !(reopen_inaccessible_files && fd == -1);
1136 if (fd == -1)
1138 if (forever)
1140 f->fd = -1;
1141 f->errnum = errno;
1142 f->ignore = 0;
1143 f->ino = 0;
1144 f->dev = 0;
1146 error (0, errno, "%s", pretty_name (f));
1147 errors = 1;
1149 else
1151 if (print_headers)
1152 write_header (pretty_name (f));
1153 errors = tail (pretty_name (f), fd, n_units);
1154 if (forever)
1156 f->errnum = 0;
1157 /* FIXME: duplicate code */
1158 if (fstat (fd, &stats) < 0)
1160 errors = 1;
1161 f->errnum = errno;
1162 error (0, errno, "%s", pretty_name (f));
1164 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1166 error (0, 0, _("%s: cannot follow end of this type of file;\
1167 giving up on this name"),
1168 pretty_name (f));
1169 errors = 1;
1170 f->errnum = -1;
1171 f->ignore = 1;
1174 if (errors)
1176 close_fd (fd, pretty_name (f));
1177 f->fd = -1;
1179 else
1181 f->fd = fd;
1182 f->size = stats.st_size;
1183 f->dev = stats.st_dev;
1184 f->ino = stats.st_ino;
1185 f->n_unchanged_stats = 0;
1186 f->n_consecutive_size_changes = 0;
1187 f->ignore = 0;
1190 else
1192 if (!is_stdin && close (fd))
1194 error (0, errno, "%s", pretty_name (f));
1195 errors = 1;
1200 return errors;
1203 /* If the command line arguments are of the obsolescent form and the
1204 option string is well-formed, set *FAIL to zero, set *N_UNITS, the
1205 globals COUNT_LINES, FOREVER, and FROM_START, and return non-zero.
1206 Otherwise, if the command line arguments appear to be of the
1207 obsolescent form but the option string is malformed, set *FAIL to
1208 non-zero, don't modify any other parameter or global variable, and
1209 return non-zero. Otherwise, return zero and don't modify any parameter
1210 or global variable. */
1212 static int
1213 parse_obsolescent_option (int argc, const char *const *argv,
1214 off_t *n_units, int *fail)
1216 const char *p = argv[1];
1217 const char *n_string = NULL;
1218 const char *n_string_end;
1220 int t_from_start;
1221 int t_count_lines;
1222 int t_forever;
1224 /* With the obsolescent form, there is one option string and
1225 (technically) at most one file argument. But we allow two or more
1226 by default. */
1227 if (argc < 2)
1228 return 0;
1230 /* If P starts with `+', `-N' (where N is a digit), or `-l',
1231 then it is obsolescent. Return zero otherwise. */
1232 if ( ! (p[0] == '+' || (p[0] == '-' && (p[1] == 'l' || ISDIGIT (p[1])))) )
1233 return 0;
1235 if (*p == '+')
1236 t_from_start = 1;
1237 else if (*p == '-')
1238 t_from_start = 0;
1239 else
1240 return 0;
1242 ++p;
1243 if (ISDIGIT (*p))
1245 n_string = p;
1248 ++p;
1250 while (ISDIGIT (*p));
1252 n_string_end = p;
1254 t_count_lines = 1;
1255 if (*p == 'c')
1257 t_count_lines = 0;
1258 ++p;
1260 else if (*p == 'l')
1262 ++p;
1265 t_forever = 0;
1266 if (*p == 'f')
1268 t_forever = 1;
1269 ++p;
1272 if (*p != '\0')
1274 /* If (argv[1] begins with a `+' or if it begins with `-' followed
1275 by a digit), but has an invalid suffix character, give a diagnostic
1276 and indicate to caller that this *is* of the obsolescent form,
1277 but that it's an invalid option. */
1278 if (t_from_start || n_string)
1280 error (0, 0,
1281 _("%c: invalid suffix character in obsolescent option" ), *p);
1282 *fail = 1;
1283 return 1;
1286 /* Otherwise, it might be a valid non-obsolescent option like -n. */
1287 return 0;
1290 *fail = 0;
1291 if (n_string == NULL)
1292 *n_units = DEFAULT_N_LINES;
1293 else
1295 strtol_error s_err;
1296 unsigned long int tmp_ulong;
1297 char *end;
1298 s_err = xstrtoul (n_string, &end, 10, &tmp_ulong, NULL);
1299 if (s_err == LONGINT_OK && tmp_ulong <= OFF_T_MAX)
1300 *n_units = (off_t) tmp_ulong;
1301 else
1303 /* Extract a NUL-terminated string for the error message. */
1304 size_t len = n_string_end - n_string;
1305 char *n_string_tmp = xmalloc (len + 1);
1307 strncpy (n_string_tmp, n_string, len);
1308 n_string_tmp[len] = '\0';
1310 error (0, 0,
1311 _("%s: %s is so large that it is not representable"),
1312 n_string_tmp, (count_lines
1313 ? _("number of lines")
1314 : _("number of bytes")));
1315 free (n_string_tmp);
1316 *fail = 1;
1320 if (!*fail)
1322 if (argc > 3)
1324 int posix_pedantic = (getenv ("POSIXLY_CORRECT") != NULL);
1326 /* When POSIXLY_CORRECT is set, enforce the `at most one
1327 file argument' requirement. */
1328 if (posix_pedantic)
1330 error (0, 0, _("\
1331 too many arguments; When using tail's obsolescent option syntax (%s)\n\
1332 there may be no more than one file argument. Use the equivalent -n or -c\n\
1333 option instead."), argv[1]);
1334 *fail = 1;
1335 return 1;
1338 #if DISABLED /* FIXME: enable or remove this warning. */
1339 error (0, 0, _("\
1340 Warning: it is not portable to use two or more file arguments with\n\
1341 tail's obsolescent option syntax (%s). Use the equivalent -n or -c\n\
1342 option instead."), argv[1]);
1343 #endif
1346 /* Set globals. */
1347 from_start = t_from_start;
1348 count_lines = t_count_lines;
1349 forever = t_forever;
1352 return 1;
1355 static void
1356 parse_options (int argc, char **argv,
1357 off_t *n_units, enum header_mode *header_mode)
1359 int c;
1361 count_lines = 1;
1362 forever = from_start = print_headers = 0;
1364 while ((c = getopt_long (argc, argv, "c:n:fqs:v", long_options, NULL))
1365 != -1)
1367 switch (c)
1369 case 0:
1370 break;
1372 case 'c':
1373 case 'n':
1374 count_lines = (c == 'n');
1375 if (*optarg == '+')
1376 from_start = 1;
1377 else if (*optarg == '-')
1378 ++optarg;
1381 strtol_error s_err;
1382 uintmax_t n;
1383 s_err = xstrtoumax (optarg, NULL, 10, &n, "bkm");
1384 if (s_err == LONGINT_INVALID)
1386 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1387 (c == 'n'
1388 ? _("invalid number of lines")
1389 : _("invalid number of bytes")));
1392 if (s_err != LONGINT_OK)
1393 error (EXIT_FAILURE, 0,
1394 _("%s: is so large that it is not representable"), optarg);
1396 if (OFF_T_MAX < n)
1397 error (EXIT_FAILURE, 0,
1398 _("%s is larger than the maximum file size on this system"),
1399 optarg);
1400 *n_units = (off_t) n;
1402 break;
1404 case 'f':
1405 case LONG_FOLLOW_OPTION:
1406 forever = 1;
1407 if (optarg == NULL)
1408 follow_mode = DEFAULT_FOLLOW_MODE;
1409 else
1410 follow_mode = XARGMATCH ("--follow", optarg,
1411 follow_mode_string, follow_mode_map);
1412 break;
1414 case RETRY_OPTION:
1415 reopen_inaccessible_files = 1;
1416 break;
1418 case MAX_UNCHANGED_STATS_OPTION:
1419 /* --max-unchanged-stats=N */
1420 if (xstrtoul (optarg, NULL, 10,
1421 &max_n_unchanged_stats_between_opens, "") != LONGINT_OK)
1423 error (EXIT_FAILURE, 0,
1424 _("%s: invalid maximum number of unchanged stats between opens"),
1425 optarg);
1427 break;
1429 case MAX_CONSECUTIVE_SIZE_CHANGES_OPTION:
1430 /* --max-consecutive-size-changes=N */
1431 if (xstrtoul (optarg, NULL, 10,
1432 &max_n_consecutive_size_changes_between_opens, "")
1433 != LONGINT_OK)
1435 error (EXIT_FAILURE, 0,
1436 _("%s: invalid maximum number of consecutive size changes"),
1437 optarg);
1439 break;
1441 case PID_OPTION:
1443 strtol_error s_err;
1444 unsigned long int tmp_ulong;
1445 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1446 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1448 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1450 pid = tmp_ulong;
1452 break;
1454 case 'q':
1455 *header_mode = never;
1456 break;
1458 case 's':
1460 strtol_error s_err;
1461 unsigned long int tmp_ulong;
1462 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1463 if (s_err != LONGINT_OK || tmp_ulong > UINT_MAX)
1465 error (EXIT_FAILURE, 0,
1466 _("%s: invalid number of seconds"), optarg);
1468 sleep_interval = tmp_ulong;
1470 break;
1472 case 'v':
1473 *header_mode = always;
1474 break;
1476 case_GETOPT_HELP_CHAR;
1478 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1480 default:
1481 usage (1);
1485 if (reopen_inaccessible_files && follow_mode != Follow_name)
1486 error (0, 0, _("warning: --retry is useful only when following by name"));
1488 if (pid && !forever)
1489 error (0, 0,
1490 _("warning: PID ignored; --pid=PID is useful only when following"));
1491 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
1493 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1494 pid = 0;
1499 main (int argc, char **argv)
1501 enum header_mode header_mode = multiple_files;
1502 int exit_status = 0;
1503 /* If from_start, the number of items to skip before printing; otherwise,
1504 the number of items at the end of the file to print. Although the type
1505 is signed, the value is never negative. */
1506 off_t n_units = DEFAULT_N_LINES;
1507 int n_files;
1508 char **file;
1509 struct File_spec *F;
1510 int i;
1512 program_name = argv[0];
1513 setlocale (LC_ALL, "");
1514 bindtextdomain (PACKAGE, LOCALEDIR);
1515 textdomain (PACKAGE);
1517 atexit (close_stdout);
1519 have_read_stdin = 0;
1522 int found_obsolescent;
1523 int fail;
1524 found_obsolescent = parse_obsolescent_option (argc,
1525 (const char *const *) argv,
1526 &n_units, &fail);
1527 if (found_obsolescent)
1529 if (fail)
1530 exit (EXIT_FAILURE);
1531 optind = 2;
1533 else
1535 parse_options (argc, argv, &n_units, &header_mode);
1539 /* To start printing with item N_UNITS from the start of the file, skip
1540 N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix
1541 compatibility it's treated the same as `tail +1'. */
1542 if (from_start)
1544 if (n_units)
1545 --n_units;
1548 n_files = argc - optind;
1549 file = argv + optind;
1551 if (n_files == 0)
1553 static char *dummy_stdin = "-";
1554 n_files = 1;
1555 file = &dummy_stdin;
1558 F = (struct File_spec *) xmalloc (n_files * sizeof (F[0]));
1559 for (i = 0; i < n_files; i++)
1560 F[i].name = file[i];
1562 if (header_mode == always
1563 || (header_mode == multiple_files && n_files > 1))
1564 print_headers = 1;
1566 for (i = 0; i < n_files; i++)
1567 exit_status |= tail_file (&F[i], n_units);
1569 if (forever)
1571 /* This fflush appears to be required only on Solaris2.7. */
1572 if (fflush (stdout) < 0)
1573 error (EXIT_FAILURE, errno, _("write error"));
1575 SETVBUF (stdout, NULL, _IONBF, 0);
1576 tail_forever (F, n_files);
1579 if (have_read_stdin && close (0) < 0)
1580 error (EXIT_FAILURE, errno, "-");
1581 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);