(recheck): Handle a race condition (including <dev,inode>
[coreutils.git] / src / tail.c
blob7a2c32506f17b01a56a3915f5b60a4cf1309af03
1 /* tail -- output the last part of file(s)
2 Copyright (C) 89, 90, 91, 1995-1999 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
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 "argmatch.h"
36 #include "error.h"
37 #include "safe-read.h"
38 #include "xstrtol.h"
40 /* The official name of this program (e.g., no `g' prefix). */
41 #define PROGRAM_NAME "tail"
43 #define AUTHORS \
44 "Paul Rubin, David MacKenzie, Ian Lance Taylor, and Jim Meyering"
46 #ifndef OFF_T_MIN
47 # define OFF_T_MIN TYPE_MINIMUM (off_t)
48 #endif
50 #ifndef OFF_T_MAX
51 # define OFF_T_MAX TYPE_MAXIMUM (off_t)
52 #endif
54 #ifndef ENOSYS
55 /* Some systems don't have ENOSYS -- this should be a big enough
56 value that no valid errno value will match it. */
57 # define ENOSYS 99999
58 #endif
60 /* Number of items to tail. */
61 #define DEFAULT_N_LINES 10
63 /* Size of atomic reads. */
64 #ifndef BUFSIZ
65 # define BUFSIZ (512 * 8)
66 #endif
68 /* A special value for dump_remainder's N_BYTES parameter. */
69 #define COPY_TO_EOF OFF_T_MAX
71 /* FIXME: make Follow_name the default? */
72 #define DEFAULT_FOLLOW_MODE Follow_descriptor
74 enum Follow_mode
76 /* Follow the name of each file: if the file is renamed, try to reopen
77 that name and track the end of the new file if/when it's recreated.
78 This is useful for tracking logs that are occasionally rotated. */
79 Follow_name = 1,
81 /* Follow each descriptor obtained upon opening a file.
82 That means we'll continue to follow the end of a file even after
83 it has been renamed or unlinked. */
84 Follow_descriptor = 2
87 static char const *const follow_mode_string[] =
89 "descriptor", "name", 0
92 static enum Follow_mode const follow_mode_map[] =
94 Follow_descriptor, Follow_name,
97 struct File_spec
99 /* The actual file name, or "-" for stdin. */
100 char *name;
102 /* File descriptor on which the file is open; -1 if it's not open. */
103 int fd;
105 /* The size of the file the last time we checked. */
106 off_t size;
108 /* The device and inode of the file the last time we checked. */
109 dev_t dev;
110 ino_t ino;
112 /* See description of DEFAULT_MAX_N_... below. */
113 unsigned int n_unchanged_stats;
115 /* See description of DEFAULT_MAX_N_... below. */
116 unsigned int n_consecutive_size_changes;
118 /* A file is tailable if it is a regular file or a fifo and it is
119 readable. */
120 int tailable;
122 /* The value of errno seen last time we checked this file. */
123 int errnum;
127 /* Keep trying to open a file even if it is inaccessible when tail starts
128 or if it becomes inaccessible later -- useful only with -f. */
129 static int reopen_inaccessible_files;
131 /* If nonzero, interpret the numeric argument as the number of lines.
132 Otherwise, interpret it as the number of bytes. */
133 static int count_lines;
135 /* Whether we follow the name of each file or the file descriptor
136 that is initially associated with each name. */
137 static enum Follow_mode follow_mode = Follow_descriptor;
139 /* If nonzero, read from the ends of all specified files until killed. */
140 static int forever;
142 /* If nonzero, count from start of file instead of end. */
143 static int from_start;
145 /* If nonzero, print filename headers. */
146 static int print_headers;
148 /* When to print the filename banners. */
149 enum header_mode
151 multiple_files, always, never
154 /* When tailing a file by name, if there have been this many consecutive
155 iterations for which the size has remained the same, then open/fstat
156 the file to determine if that file name is still associated with the
157 same device/inode-number pair as before. This option is meaningful only
158 when following by name. --max-unchanged-stats=N */
159 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
160 static unsigned long max_n_unchanged_stats_between_opens =
161 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
163 /* This variable is used to ensure that a file that is unlinked or moved
164 aside, yet always growing will be recognized as having been renamed.
165 After detecting this many consecutive size changes for a file, open/fstat
166 the file to determine if that file name is still associated with the
167 same device/inode-number pair as before. This option is meaningful only
168 when following by name. --max-consecutive-size-changes=N */
169 #define DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES 200
170 static unsigned long max_n_consecutive_size_changes_between_opens =
171 DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES;
173 /* The name this program was run with. */
174 char *program_name;
176 /* The number of seconds to sleep between iterations.
177 During one iteration, every file name or descriptor is checked to
178 see if it has changed. */
179 /* FIXME: allow fractional seconds */
180 static unsigned int sleep_interval = 1;
182 /* The process ID of the process (presumably on the current host)
183 that is writing to all followed files. */
184 static pid_t pid;
186 /* Nonzero if we have ever read standard input. */
187 static int have_read_stdin;
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. */
191 enum
193 RETRY_OPTION = CHAR_MAX + 1,
194 MAX_UNCHANGED_STATS_OPTION,
195 MAX_CONSECUTIVE_SIZE_CHANGES_OPTION,
196 PID_OPTION,
197 LONG_FOLLOW_OPTION,
200 static struct option const long_options[] =
202 /* --allow-missing is deprecated; use --retry instead
203 FIXME: remove it some day */
204 {"allow-missing", no_argument, NULL, RETRY_OPTION},
205 {"bytes", required_argument, NULL, 'c'},
206 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
207 {"lines", required_argument, NULL, 'n'},
208 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
209 {"max-consecutive-size-changes", required_argument, NULL,
210 MAX_CONSECUTIVE_SIZE_CHANGES_OPTION},
211 {"pid", required_argument, NULL, PID_OPTION},
212 {"quiet", no_argument, NULL, 'q'},
213 {"retry", no_argument, NULL, RETRY_OPTION},
214 {"silent", no_argument, NULL, 'q'},
215 {"sleep-interval", required_argument, NULL, 's'},
216 {"verbose", no_argument, NULL, 'v'},
217 {GETOPT_HELP_OPTION_DECL},
218 {GETOPT_VERSION_OPTION_DECL},
219 {NULL, 0, NULL, 0}
222 void
223 usage (int status)
225 if (status != 0)
226 fprintf (stderr, _("Try `%s --help' for more information.\n"),
227 program_name);
228 else
230 printf (_("\
231 Usage: %s [OPTION]... [FILE]...\n\
233 program_name);
234 printf (_("\
235 Print the last %d lines of each FILE to standard output.\n\
236 With more than one FILE, precede each with a header giving the file name.\n\
237 With no FILE, or when FILE is -, read standard input.\n\
239 --retry keep trying to open a file even if it is\n\
240 inaccessible when tail starts or if it becomes\n\
241 inaccessible later -- useful only with -f\n\
242 -c, --bytes=N output the last N bytes\n\
243 -f, --follow[={name|descriptor}] output appended data as the file grows;\n\
244 -f, --follow, and --follow=descriptor are\n\
245 equivalent\n\
246 -n, --lines=N output the last N lines, instead of the last %d\n\
247 --max-unchanged-stats=N see the texinfo documentation\n\
248 (the default is %d)\n\
249 --max-consecutive-size-changes=N see the texinfo documentation\n\
250 (the default is %d)\n\
251 --pid=PID with -f, terminate after process ID, PID dies\n\
252 -q, --quiet, --silent never output headers giving file names\n\
253 -s, --sleep-interval=S with -f, sleep S seconds between iterations\n\
254 -v, --verbose always output headers giving file names\n\
255 --help display this help and exit\n\
256 --version output version information and exit\n\
258 If the first character of N (the number of bytes or lines) is a `+',\n\
259 print beginning with the Nth item from the start of each file, otherwise,\n\
260 print the last N items in the file. N may have a multiplier suffix:\n\
261 b for 512, k for 1024, m for 1048576 (1 Meg). A first OPTION of -VALUE\n\
262 or +VALUE is treated like -n VALUE or -n +VALUE unless VALUE has one of\n\
263 the [bkm] suffix multipliers, in which case it is treated like -c VALUE\n\
264 or -c +VALUE.\n\
266 With --follow (-f), tail defaults to following the file descriptor, which\n\
267 means that even if a tail'ed file is renamed, tail will continue to track\n\
268 its end. This default behavior is not desirable when you really want to\n\
269 track the actual name of the file, not the file descriptor (e.g., log\n\
270 rotation). Use --follow=name in that case. That causes tail to track the\n\
271 named file by reopening it periodically to see if it has been removed and\n\
272 recreated by some other program.\n\
275 DEFAULT_N_LINES, DEFAULT_N_LINES,
276 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS,
277 DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES
279 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
281 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
284 static int
285 valid_file_spec (struct File_spec const *f)
287 /* Exactly one of the following subexpressions must be true. */
288 return ((f->fd == -1) ^ (f->errnum == 0));
291 static char *
292 pretty_name (struct File_spec const *f)
294 return (STREQ (f->name, "-") ? "standard input" : f->name);
297 static void
298 xwrite (int fd, char *const buffer, size_t n_bytes)
300 assert (fd == STDOUT_FILENO);
301 assert (n_bytes >= 0);
302 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
303 error (EXIT_FAILURE, errno, _("write error"));
306 static void
307 close_fd (int fd, const char *filename)
309 if (fd != -1 && fd != STDIN_FILENO && close (fd))
311 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
315 static void
316 write_header (const char *pretty_filename, const char *comment)
318 static int first_file = 1;
320 printf ("%s==> %s%s%s <==\n", (first_file ? "" : "\n"), pretty_filename,
321 (comment ? ": " : ""),
322 (comment ? comment : ""));
323 first_file = 0;
326 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
327 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
328 Return the number of bytes read from the file. */
330 static long
331 dump_remainder (const char *pretty_filename, int fd, off_t n_bytes)
333 char buffer[BUFSIZ];
334 int bytes_read;
335 long n_written;
336 off_t n_remaining = n_bytes;
338 n_written = 0;
339 while (1)
341 long n = MIN (n_remaining, (off_t) BUFSIZ);
342 bytes_read = safe_read (fd, buffer, n);
343 if (bytes_read <= 0)
344 break;
345 xwrite (STDOUT_FILENO, buffer, bytes_read);
346 n_remaining -= bytes_read;
347 n_written += bytes_read;
349 if (bytes_read == -1)
350 error (EXIT_FAILURE, errno, "%s", pretty_filename);
352 return n_written;
355 /* Print the last N_LINES lines from the end of file FD.
356 Go backward through the file, reading `BUFSIZ' bytes at a time (except
357 probably the first), until we hit the start of the file or have
358 read NUMBER newlines.
359 FILE_LENGTH is the length of the file (one more than the offset of the
360 last byte of the file).
361 Return 0 if successful, 1 if an error occurred. */
363 static int
364 file_lines (const char *pretty_filename, int fd, long int n_lines,
365 off_t file_length)
367 char buffer[BUFSIZ];
368 int bytes_read;
369 int i; /* Index into `buffer' for scanning. */
370 off_t pos = file_length;
372 if (n_lines == 0)
373 return 0;
375 /* Set `bytes_read' to the size of the last, probably partial, buffer;
376 0 < `bytes_read' <= `BUFSIZ'. */
377 bytes_read = pos % BUFSIZ;
378 if (bytes_read == 0)
379 bytes_read = BUFSIZ;
380 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
381 reads will be on block boundaries, which might increase efficiency. */
382 pos -= bytes_read;
383 /* FIXME: check lseek return value */
384 lseek (fd, pos, SEEK_SET);
385 bytes_read = safe_read (fd, buffer, bytes_read);
386 if (bytes_read == -1)
388 error (0, errno, "%s", pretty_filename);
389 return 1;
392 /* Count the incomplete line on files that don't end with a newline. */
393 if (bytes_read && buffer[bytes_read - 1] != '\n')
394 --n_lines;
398 /* Scan backward, counting the newlines in this bufferfull. */
399 for (i = bytes_read - 1; i >= 0; i--)
401 /* Have we counted the requested number of newlines yet? */
402 if (buffer[i] == '\n' && n_lines-- == 0)
404 /* If this newline wasn't the last character in the buffer,
405 print the text after it. */
406 if (i != bytes_read - 1)
407 xwrite (STDOUT_FILENO, &buffer[i + 1], bytes_read - (i + 1));
408 dump_remainder (pretty_filename, fd,
409 file_length - (pos + bytes_read));
410 return 0;
413 /* Not enough newlines in that bufferfull. */
414 if (pos == 0)
416 /* Not enough lines in the file; print the entire file. */
417 /* FIXME: check lseek return value */
418 lseek (fd, (off_t) 0, SEEK_SET);
419 dump_remainder (pretty_filename, fd, file_length);
420 return 0;
422 pos -= BUFSIZ;
423 /* FIXME: check lseek return value */
424 lseek (fd, pos, SEEK_SET);
426 while ((bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0);
428 if (bytes_read == -1)
430 error (0, errno, "%s", pretty_filename);
431 return 1;
434 return 0;
437 /* Print the last N_LINES lines from the end of the standard input,
438 open for reading as pipe FD.
439 Buffer the text as a linked list of LBUFFERs, adding them as needed.
440 Return 0 if successful, 1 if an error occured. */
442 static int
443 pipe_lines (const char *pretty_filename, int fd, long int n_lines)
445 struct linebuffer
447 int nbytes, nlines;
448 char buffer[BUFSIZ];
449 struct linebuffer *next;
451 typedef struct linebuffer LBUFFER;
452 LBUFFER *first, *last, *tmp;
453 int i; /* Index into buffers. */
454 int total_lines = 0; /* Total number of newlines in all buffers. */
455 int errors = 0;
457 first = last = (LBUFFER *) xmalloc (sizeof (LBUFFER));
458 first->nbytes = first->nlines = 0;
459 first->next = NULL;
460 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
462 /* Input is always read into a fresh buffer. */
463 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
465 tmp->nlines = 0;
466 tmp->next = NULL;
468 /* Count the number of newlines just read. */
469 for (i = 0; i < tmp->nbytes; i++)
470 if (tmp->buffer[i] == '\n')
471 ++tmp->nlines;
472 total_lines += tmp->nlines;
474 /* If there is enough room in the last buffer read, just append the new
475 one to it. This is because when reading from a pipe, `nbytes' can
476 often be very small. */
477 if (tmp->nbytes + last->nbytes < BUFSIZ)
479 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
480 last->nbytes += tmp->nbytes;
481 last->nlines += tmp->nlines;
483 else
485 /* If there's not enough room, link the new buffer onto the end of
486 the list, then either free up the oldest buffer for the next
487 read if that would leave enough lines, or else malloc a new one.
488 Some compaction mechanism is possible but probably not
489 worthwhile. */
490 last = last->next = tmp;
491 if (total_lines - first->nlines > n_lines)
493 tmp = first;
494 total_lines -= first->nlines;
495 first = first->next;
497 else
498 tmp = (LBUFFER *) xmalloc (sizeof (LBUFFER));
501 if (tmp->nbytes == -1)
503 error (0, errno, "%s", pretty_filename);
504 errors = 1;
505 free ((char *) tmp);
506 goto free_lbuffers;
509 free ((char *) tmp);
511 /* This prevents a core dump when the pipe contains no newlines. */
512 if (n_lines == 0)
513 goto free_lbuffers;
515 /* Count the incomplete line on files that don't end with a newline. */
516 if (last->buffer[last->nbytes - 1] != '\n')
518 ++last->nlines;
519 ++total_lines;
522 /* Run through the list, printing lines. First, skip over unneeded
523 buffers. */
524 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
525 total_lines -= tmp->nlines;
527 /* Find the correct beginning, then print the rest of the file. */
528 if (total_lines > n_lines)
530 char *cp;
532 /* Skip `total_lines' - `n_lines' newlines. We made sure that
533 `total_lines' - `n_lines' <= `tmp->nlines'. */
534 cp = tmp->buffer;
535 for (i = total_lines - n_lines; i; --i)
536 while (*cp++ != '\n')
537 /* Do nothing. */ ;
538 i = cp - tmp->buffer;
540 else
541 i = 0;
542 xwrite (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
544 for (tmp = tmp->next; tmp; tmp = tmp->next)
545 xwrite (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
547 free_lbuffers:
548 while (first)
550 tmp = first->next;
551 free ((char *) first);
552 first = tmp;
554 return errors;
557 /* Print the last N_BYTES characters from the end of pipe FD.
558 This is a stripped down version of pipe_lines.
559 Return 0 if successful, 1 if an error occurred. */
561 static int
562 pipe_bytes (const char *pretty_filename, int fd, off_t n_bytes)
564 struct charbuffer
566 int nbytes;
567 char buffer[BUFSIZ];
568 struct charbuffer *next;
570 typedef struct charbuffer CBUFFER;
571 CBUFFER *first, *last, *tmp;
572 int i; /* Index into buffers. */
573 int total_bytes = 0; /* Total characters in all buffers. */
574 int errors = 0;
576 first = last = (CBUFFER *) xmalloc (sizeof (CBUFFER));
577 first->nbytes = 0;
578 first->next = NULL;
579 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
581 /* Input is always read into a fresh buffer. */
582 while ((tmp->nbytes = safe_read (fd, tmp->buffer, BUFSIZ)) > 0)
584 tmp->next = NULL;
586 total_bytes += tmp->nbytes;
587 /* If there is enough room in the last buffer read, just append the new
588 one to it. This is because when reading from a pipe, `nbytes' can
589 often be very small. */
590 if (tmp->nbytes + last->nbytes < BUFSIZ)
592 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
593 last->nbytes += tmp->nbytes;
595 else
597 /* If there's not enough room, link the new buffer onto the end of
598 the list, then either free up the oldest buffer for the next
599 read if that would leave enough characters, or else malloc a new
600 one. Some compaction mechanism is possible but probably not
601 worthwhile. */
602 last = last->next = tmp;
603 if (total_bytes - first->nbytes > n_bytes)
605 tmp = first;
606 total_bytes -= first->nbytes;
607 first = first->next;
609 else
611 tmp = (CBUFFER *) xmalloc (sizeof (CBUFFER));
615 if (tmp->nbytes == -1)
617 error (0, errno, "%s", pretty_filename);
618 errors = 1;
619 free ((char *) tmp);
620 goto free_cbuffers;
623 free ((char *) tmp);
625 /* Run through the list, printing characters. First, skip over unneeded
626 buffers. */
627 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
628 total_bytes -= tmp->nbytes;
630 /* Find the correct beginning, then print the rest of the file.
631 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
632 if (total_bytes > n_bytes)
633 i = total_bytes - n_bytes;
634 else
635 i = 0;
636 xwrite (STDOUT_FILENO, &tmp->buffer[i], tmp->nbytes - i);
638 for (tmp = tmp->next; tmp; tmp = tmp->next)
639 xwrite (STDOUT_FILENO, tmp->buffer, tmp->nbytes);
641 free_cbuffers:
642 while (first)
644 tmp = first->next;
645 free ((char *) first);
646 first = tmp;
648 return errors;
651 /* Skip N_BYTES characters from the start of pipe FD, and print
652 any extra characters that were read beyond that.
653 Return 1 on error, 0 if ok. */
655 static int
656 start_bytes (const char *pretty_filename, int fd, off_t n_bytes)
658 char buffer[BUFSIZ];
659 int bytes_read = 0;
661 while (n_bytes > 0 && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
662 n_bytes -= bytes_read;
663 if (bytes_read == -1)
665 error (0, errno, "%s", pretty_filename);
666 return 1;
668 else if (n_bytes < 0)
669 xwrite (STDOUT_FILENO, &buffer[bytes_read + n_bytes], -n_bytes);
670 return 0;
673 /* Skip N_LINES lines at the start of file or pipe FD, and print
674 any extra characters that were read beyond that.
675 Return 1 on error, 0 if ok. */
677 static int
678 start_lines (const char *pretty_filename, int fd, long int n_lines)
680 char buffer[BUFSIZ];
681 int bytes_read = 0;
682 int bytes_to_skip = 0;
684 while (n_lines && (bytes_read = safe_read (fd, buffer, BUFSIZ)) > 0)
686 bytes_to_skip = 0;
687 while (bytes_to_skip < bytes_read)
688 if (buffer[bytes_to_skip++] == '\n' && --n_lines == 0)
689 break;
691 if (bytes_read == -1)
693 error (0, errno, "%s", pretty_filename);
694 return 1;
696 else if (bytes_to_skip < bytes_read)
698 xwrite (STDOUT_FILENO, &buffer[bytes_to_skip],
699 bytes_read - bytes_to_skip);
701 return 0;
704 /* FIXME: describe */
706 static void
707 recheck (struct File_spec *f)
709 /* open/fstat the file and announce if dev/ino have changed */
710 struct stat new_stats;
711 int fd;
712 int fail = 0;
713 int is_stdin = (STREQ (f->name, "-"));
714 int was_tailable = f->tailable;
715 int prev_errnum = f->errnum;
716 int new_file;
718 assert (valid_file_spec (f));
720 fd = (is_stdin ? STDIN_FILENO : open (f->name, O_RDONLY));
722 /* If the open fails because the file doesn't exist,
723 then mark the file as not tailable. */
724 f->tailable = !(reopen_inaccessible_files && fd == -1);
726 if (fd == -1 || fstat (fd, &new_stats) < 0)
728 fail = 1;
729 f->errnum = errno;
730 if (!f->tailable)
732 if (was_tailable)
734 /* FIXME-maybe: detect the case in which the file first becomes
735 unreadable (perms), and later becomes readable again and can
736 be seen to be the same file (dev/ino). Otherwise, tail prints
737 the entire contents of the file when it becomes readable. */
738 error (0, f->errnum, _("`%s' has become inaccessible"),
739 pretty_name (f));
741 else
743 /* say nothing... it's still not tailable */
746 else if (prev_errnum != errno)
748 error (0, errno, "%s", pretty_name (f));
751 else
753 f->errnum = 0;
756 new_file = 0;
757 if (fail)
759 close_fd (fd, pretty_name (f));
760 close_fd (f->fd, pretty_name (f));
761 f->fd = -1;
763 else if (prev_errnum && prev_errnum != ENOENT)
765 new_file = 1;
766 assert (f->fd == -1);
767 error (0, 0, _("`%s' has become accessible"), pretty_name (f));
769 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
771 new_file = 1;
772 if (f->fd == -1)
774 error (0, 0,
775 _("`%s' has appeared; following end of new file"),
776 pretty_name (f));
778 else
780 /* Close the old one. */
781 close_fd (f->fd, pretty_name (f));
783 /* File has been replaced (e.g., via log rotation) --
784 tail the new one. */
785 error (0, 0,
786 _("`%s' has been replaced; following end of new file"),
787 pretty_name (f));
790 else
792 if (f->fd == -1)
794 /* This happens when one iteration finds the file missing,
795 then the preceding <dev,inode> pair is reused as the
796 file is recreated. */
797 new_file = 1;
799 else
801 close_fd (fd, pretty_name (f));
805 if (new_file)
807 /* Record new file info in f. */
808 f->fd = fd;
809 f->size = 0; /* Start at the beginning of the file... */
810 f->dev = new_stats.st_dev;
811 f->ino = new_stats.st_ino;
812 f->n_unchanged_stats = 0;
813 f->n_consecutive_size_changes = 0;
814 /* FIXME: check lseek return value */
815 lseek (f->fd, f->size, SEEK_SET);
819 /* FIXME: describe */
821 static unsigned int
822 n_live_files (const struct File_spec *f, int n_files)
824 int i;
825 unsigned int n_live = 0;
827 for (i = 0; i < n_files; i++)
829 if (f[i].fd >= 0)
830 ++n_live;
832 return n_live;
835 /* Tail NFILES files forever, or until killed.
836 The pertinent information for each file is stored in an entry of F.
837 Loop over each of them, doing an fstat to see if they have changed size,
838 and an occasional open/fstat to see if any dev/ino pair has changed.
839 If none of them have changed size in one iteration, sleep for a
840 while and try again. Continue until the user interrupts us. */
842 static void
843 tail_forever (struct File_spec *f, int nfiles)
845 int last;
846 int writer_is_dead = 0;
848 last = nfiles - 1;
850 while (1)
852 int i;
853 int any_changed;
855 any_changed = 0;
856 for (i = 0; i < nfiles; i++)
858 struct stat stats;
860 if (f[i].fd < 0)
862 recheck (&f[i]);
863 continue;
866 if (fstat (f[i].fd, &stats) < 0)
868 f[i].fd = -1;
869 f[i].errnum = errno;
870 error (0, errno, "%s", pretty_name (&f[i]));
871 continue;
874 if (stats.st_size == f[i].size)
876 f[i].n_consecutive_size_changes = 0;
877 if (++f[i].n_unchanged_stats > max_n_unchanged_stats_between_opens
878 && follow_mode == Follow_name)
880 recheck (&f[i]);
881 f[i].n_unchanged_stats = 0;
883 continue;
886 /* Size changed. */
887 ++f[i].n_consecutive_size_changes;
889 /* Ensure that a file that's unlinked or moved aside, yet always
890 growing will be recognized as having been renamed. */
891 if (follow_mode == Follow_name
892 && (f[i].n_consecutive_size_changes
893 > max_n_consecutive_size_changes_between_opens))
895 f[i].n_consecutive_size_changes = 0;
896 recheck (&f[i]);
897 continue;
900 /* This file has changed size. Print out what we can, and
901 then keep looping. */
903 any_changed = 1;
905 /* reset counter */
906 f[i].n_unchanged_stats = 0;
908 if (stats.st_size < f[i].size)
910 write_header (pretty_name (&f[i]), _("file truncated"));
911 last = i;
912 /* FIXME: check lseek return value */
913 lseek (f[i].fd, stats.st_size, SEEK_SET);
914 f[i].size = stats.st_size;
915 continue;
918 if (i != last)
920 if (print_headers)
921 write_header (pretty_name (&f[i]), NULL);
922 last = i;
924 f[i].size += dump_remainder (pretty_name (&f[i]), f[i].fd,
925 COPY_TO_EOF);
928 if (n_live_files (f, nfiles) == 0 && ! reopen_inaccessible_files)
930 error (0, 0, _("no files remaining"));
931 break;
934 /* If none of the files changed size, sleep. */
935 if (!any_changed)
937 if (writer_is_dead)
938 break;
939 sleep (sleep_interval);
941 /* Once the writer is dead, read the files once more to
942 avoid a race condition. */
943 writer_is_dead = (pid != 0
944 && kill (pid, 0) != 0
945 /* Handle the case in which you cannot send a
946 signal to the writer, so kill fails and sets
947 errno to EPERM. */
948 && errno != EPERM);
953 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
954 Return 0 if successful, 1 if an error occurred. */
956 static int
957 tail_bytes (const char *pretty_filename, int fd, off_t n_bytes)
959 struct stat stats;
961 /* We need binary input, since `tail' relies on `lseek' and byte counts,
962 while binary output will preserve the style (Unix/DOS) of text file. */
963 SET_BINARY2 (fd, STDOUT_FILENO);
965 if (fstat (fd, &stats))
967 error (0, errno, "%s", pretty_filename);
968 return 1;
971 if (from_start)
973 if (S_ISREG (stats.st_mode))
975 /* FIXME: check lseek return value */
976 lseek (fd, n_bytes, SEEK_CUR);
978 else if (start_bytes (pretty_filename, fd, n_bytes))
980 return 1;
982 dump_remainder (pretty_filename, fd, COPY_TO_EOF);
984 else
986 if (S_ISREG (stats.st_mode))
988 off_t current_pos, end_pos;
989 size_t bytes_remaining;
991 if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1
992 && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1)
994 off_t diff;
995 /* Be careful here. The current position may actually be
996 beyond the end of the file. */
997 bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
999 else
1001 error (0, errno, "%s", pretty_filename);
1002 return 1;
1005 if (bytes_remaining <= n_bytes)
1007 /* From the current position to end of file, there are no
1008 more bytes than have been requested. So reposition the
1009 file pointer to the incoming current position and print
1010 everything after that. */
1011 /* FIXME: check lseek return value */
1012 lseek (fd, current_pos, SEEK_SET);
1014 else
1016 /* There are more bytes remaining than were requested.
1017 Back up. */
1018 /* FIXME: check lseek return value */
1019 lseek (fd, -n_bytes, SEEK_END);
1021 dump_remainder (pretty_filename, fd, n_bytes);
1023 else
1024 return pipe_bytes (pretty_filename, fd, n_bytes);
1026 return 0;
1029 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1030 Return 0 if successful, 1 if an error occurred. */
1032 static int
1033 tail_lines (const char *pretty_filename, int fd, long int n_lines)
1035 struct stat stats;
1036 off_t length;
1038 /* We need binary input, since `tail' relies on `lseek' and byte counts,
1039 while binary output will preserve the style (Unix/DOS) of text file. */
1040 SET_BINARY2 (fd, STDOUT_FILENO);
1042 if (fstat (fd, &stats))
1044 error (0, errno, "%s", pretty_filename);
1045 return 1;
1048 if (from_start)
1050 if (start_lines (pretty_filename, fd, n_lines))
1051 return 1;
1052 dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1054 else
1056 /* Use file_lines only if FD refers to a regular file with
1057 its file pointer positioned at beginning of file. */
1058 /* FIXME: adding the lseek conjunct is a kludge.
1059 Once there's a reasonable test suite, fix the true culprit:
1060 file_lines. file_lines shouldn't presume that the input
1061 file pointer is initially positioned to beginning of file. */
1062 if (S_ISREG (stats.st_mode)
1063 && lseek (fd, (off_t) 0, SEEK_CUR) == (off_t) 0)
1065 length = lseek (fd, (off_t) 0, SEEK_END);
1066 if (length != 0 && file_lines (pretty_filename, fd, n_lines, length))
1067 return 1;
1069 else
1070 return pipe_lines (pretty_filename, fd, n_lines);
1072 return 0;
1075 /* Display the last N_UNITS units of file FILENAME, open for reading
1076 in FD.
1077 Return 0 if successful, 1 if an error occurred. */
1079 static int
1080 tail (const char *pretty_filename, int fd, off_t n_units)
1082 if (count_lines)
1083 return tail_lines (pretty_filename, fd, (long) n_units);
1084 else
1085 return tail_bytes (pretty_filename, fd, n_units);
1088 /* Display the last N_UNITS units of the file described by F.
1089 Return 0 if successful, 1 if an error occurred. */
1091 static int
1092 tail_file (struct File_spec *f, off_t n_units)
1094 int fd, errors;
1095 struct stat stats;
1097 int is_stdin = (STREQ (f->name, "-"));
1099 if (is_stdin)
1101 have_read_stdin = 1;
1102 fd = STDIN_FILENO;
1104 else
1106 fd = open (f->name, O_RDONLY);
1109 f->tailable = !(reopen_inaccessible_files && fd == -1);
1111 if (fd == -1)
1113 if (forever)
1115 f->fd = -1;
1116 f->errnum = errno;
1118 error (0, errno, "%s", pretty_name (f));
1119 errors = 1;
1121 else
1123 if (print_headers)
1124 write_header (pretty_name (f), NULL);
1125 errors = tail (pretty_name (f), fd, n_units);
1126 if (forever)
1128 f->errnum = 0;
1129 /* FIXME: duplicate code */
1130 if (fstat (fd, &stats) < 0)
1132 errors = 1;
1133 f->errnum = errno;
1134 error (0, errno, "%s", pretty_name (f));
1137 if (errors)
1139 close_fd (fd, pretty_name (f));
1140 f->fd = -1;
1142 else
1144 f->fd = fd;
1145 f->size = stats.st_size;
1146 f->dev = stats.st_dev;
1147 f->ino = stats.st_ino;
1148 f->n_unchanged_stats = 0;
1149 f->n_consecutive_size_changes = 0;
1152 else
1154 if (!is_stdin && close (fd))
1156 error (0, errno, "%s", pretty_name (f));
1157 errors = 1;
1162 return errors;
1165 /* If the command line arguments are of the obsolescent form and the
1166 option string is well-formed, set *FAIL to zero, set *N_UNITS, the
1167 globals COUNT_LINES, FOREVER, and FROM_START, and return non-zero.
1168 Otherwise, if the command line arguments appear to be of the
1169 obsolescent form but the option string is malformed, set *FAIL to
1170 non-zero, don't modify any other parameter or global variable, and
1171 return non-zero. Otherwise, return zero and don't modify any parameter
1172 or global variable. */
1174 static int
1175 parse_obsolescent_option (int argc, const char *const *argv,
1176 off_t *n_units, int *fail)
1178 const char *p = argv[1];
1179 const char *n_string = NULL;
1180 const char *n_string_end;
1182 int t_from_start;
1183 int t_count_lines;
1184 int t_forever;
1186 /* With the obsolescent form, there is one option string and
1187 (technically) at most one file argument. But we allow two or more
1188 by default. */
1189 if (argc < 2)
1190 return 0;
1192 /* If P starts with `+', `-N' (where N is a digit), or `-l',
1193 then it is obsolescent. Return zero otherwise. */
1194 if ( ! (p[0] == '+' || (p[0] == '-' && (p[1] == 'l' || ISDIGIT (p[1])))) )
1195 return 0;
1197 if (*p == '+')
1198 t_from_start = 1;
1199 else if (*p == '-')
1200 t_from_start = 0;
1201 else
1202 return 0;
1204 ++p;
1205 if (ISDIGIT (*p))
1207 n_string = p;
1210 ++p;
1212 while (ISDIGIT (*p));
1214 n_string_end = p;
1216 t_count_lines = 1;
1217 if (*p == 'c')
1219 t_count_lines = 0;
1220 ++p;
1222 else if (*p == 'l')
1224 ++p;
1227 t_forever = 0;
1228 if (*p == 'f')
1230 t_forever = 1;
1231 ++p;
1234 if (*p != '\0')
1236 /* If (argv[1] begins with a `+' or if it begins with `-' followed
1237 by a digit), but has an invalid suffix character, give a diagnostic
1238 and indicate to caller that this *is* of the obsolescent form,
1239 but that it's an invalid option. */
1240 if (t_from_start || n_string)
1242 error (0, 0,
1243 _("%c: invalid suffix character in obsolescent option" ), *p);
1244 *fail = 1;
1245 return 1;
1248 /* Otherwise, it might be a valid non-obsolescent option like -n. */
1249 return 0;
1252 *fail = 0;
1253 if (n_string == NULL)
1254 *n_units = DEFAULT_N_LINES;
1255 else
1257 strtol_error s_err;
1258 unsigned long int tmp_ulong;
1259 char *end;
1260 s_err = xstrtoul (n_string, &end, 10, &tmp_ulong, NULL);
1261 if (s_err == LONGINT_OK && tmp_ulong <= OFF_T_MAX)
1262 *n_units = (off_t) tmp_ulong;
1263 else
1265 /* Extract a NUL-terminated string for the error message. */
1266 size_t len = n_string_end - n_string;
1267 char *n_string_tmp = xmalloc (len + 1);
1269 strncpy (n_string_tmp, n_string, len);
1270 n_string_tmp[len] = '\0';
1272 error (0, 0,
1273 _("%s: %s is so large that it is not representable"),
1274 n_string_tmp, (count_lines
1275 ? _("number of lines")
1276 : _("number of bytes")));
1277 free (n_string_tmp);
1278 *fail = 1;
1282 if (!*fail)
1284 if (argc > 3)
1286 int posix_pedantic = (getenv ("POSIXLY_CORRECT") != NULL);
1288 /* When POSIXLY_CORRECT is set, enforce the `at most one
1289 file argument' requirement. */
1290 if (posix_pedantic)
1292 error (0, 0, _("\
1293 too many arguments; When using tail's obsolescent option syntax (%s)\n\
1294 there may be no more than one file argument. Use the equivalent -n or -c\n\
1295 option instead."), argv[1]);
1296 *fail = 1;
1297 return 1;
1300 #if DISABLED /* FIXME: enable or remove this warning. */
1301 error (0, 0, _("\
1302 Warning: it is not portable to use two or more file arguments with\n\
1303 tail's obsolescent option syntax (%s). Use the equivalent -n or -c\n\
1304 option instead."), argv[1]);
1305 #endif
1308 /* Set globals. */
1309 from_start = t_from_start;
1310 count_lines = t_count_lines;
1311 forever = t_forever;
1314 return 1;
1317 static void
1318 parse_options (int argc, char **argv,
1319 off_t *n_units, enum header_mode *header_mode)
1321 int c;
1323 count_lines = 1;
1324 forever = from_start = print_headers = 0;
1326 while ((c = getopt_long (argc, argv, "c:n:fqs:v", long_options, NULL))
1327 != -1)
1329 switch (c)
1331 case 0:
1332 break;
1334 case 'c':
1335 case 'n':
1336 count_lines = (c == 'n');
1337 if (*optarg == '+')
1338 from_start = 1;
1339 else if (*optarg == '-')
1340 ++optarg;
1343 strtol_error s_err;
1344 unsigned long int tmp_ulong;
1345 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "bkm");
1346 if (s_err == LONGINT_INVALID)
1348 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1349 (c == 'n'
1350 ? _("invalid number of lines")
1351 : _("invalid number of bytes")));
1353 if (s_err != LONGINT_OK || tmp_ulong > OFF_T_MAX)
1355 error (EXIT_FAILURE, 0,
1356 _("%s: %s is so large that it is not representable"),
1357 optarg,
1358 c == 'n' ? _("number of lines") : _("number of bytes"));
1360 *n_units = (off_t) tmp_ulong;
1362 break;
1364 case 'f':
1365 case LONG_FOLLOW_OPTION:
1366 forever = 1;
1367 if (optarg == NULL)
1368 follow_mode = DEFAULT_FOLLOW_MODE;
1369 else
1370 follow_mode = XARGMATCH ("--follow", optarg,
1371 follow_mode_string, follow_mode_map);
1372 break;
1374 case RETRY_OPTION:
1375 reopen_inaccessible_files = 1;
1376 break;
1378 case MAX_UNCHANGED_STATS_OPTION:
1379 /* --max-unchanged-stats=N */
1380 if (xstrtoul (optarg, NULL, 10,
1381 &max_n_unchanged_stats_between_opens, "") != LONGINT_OK)
1383 error (EXIT_FAILURE, 0,
1384 _("%s: invalid maximum number of unchanged stats between opens"),
1385 optarg);
1387 break;
1389 case MAX_CONSECUTIVE_SIZE_CHANGES_OPTION:
1390 /* --max-consecutive-size-changes=N */
1391 if (xstrtoul (optarg, NULL, 10,
1392 &max_n_consecutive_size_changes_between_opens, "")
1393 != LONGINT_OK)
1395 error (EXIT_FAILURE, 0,
1396 _("%s: invalid maximum number of consecutive size changes"),
1397 optarg);
1399 break;
1401 case PID_OPTION:
1403 strtol_error s_err;
1404 unsigned long int tmp_ulong;
1405 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1406 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1408 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1410 pid = tmp_ulong;
1412 break;
1414 case 'q':
1415 *header_mode = never;
1416 break;
1418 case 's':
1420 strtol_error s_err;
1421 unsigned long int tmp_ulong;
1422 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1423 if (s_err != LONGINT_OK || tmp_ulong > UINT_MAX)
1425 error (EXIT_FAILURE, 0,
1426 _("%s: invalid number of seconds"), optarg);
1428 sleep_interval = tmp_ulong;
1430 break;
1432 case 'v':
1433 *header_mode = always;
1434 break;
1436 case_GETOPT_HELP_CHAR;
1438 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1440 default:
1441 usage (1);
1445 if (reopen_inaccessible_files && follow_mode != Follow_name)
1446 error (0, 0, _("warning: --retry is useful only when following by name"));
1448 if (pid && !forever)
1449 error (0, 0,
1450 _("warning: PID ignored; --pid=PID is useful only when following"));
1451 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
1453 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1454 pid = 0;
1459 main (int argc, char **argv)
1461 enum header_mode header_mode = multiple_files;
1462 int exit_status = 0;
1463 /* If from_start, the number of items to skip before printing; otherwise,
1464 the number of items at the end of the file to print. Although the type
1465 is signed, the value is never negative. */
1466 off_t n_units = DEFAULT_N_LINES;
1467 int n_files;
1468 char **file;
1469 struct File_spec *F;
1470 int i;
1472 program_name = argv[0];
1473 setlocale (LC_ALL, "");
1474 bindtextdomain (PACKAGE, LOCALEDIR);
1475 textdomain (PACKAGE);
1477 have_read_stdin = 0;
1480 int found_obsolescent;
1481 int fail;
1482 found_obsolescent = parse_obsolescent_option (argc,
1483 (const char *const *) argv,
1484 &n_units, &fail);
1485 if (found_obsolescent)
1487 if (fail)
1488 exit (EXIT_FAILURE);
1489 optind = 2;
1491 else
1493 parse_options (argc, argv, &n_units, &header_mode);
1497 /* To start printing with item N_UNITS from the start of the file, skip
1498 N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix
1499 compatibility it's treated the same as `tail +1'. */
1500 if (from_start)
1502 if (n_units)
1503 --n_units;
1506 n_files = argc - optind;
1507 file = argv + optind;
1509 if (n_files == 0)
1511 static char *dummy_stdin = "-";
1512 n_files = 1;
1513 file = &dummy_stdin;
1516 F = (struct File_spec *) xmalloc (n_files * sizeof (F[0]));
1517 for (i = 0; i < n_files; i++)
1518 F[i].name = file[i];
1520 if (header_mode == always
1521 || (header_mode == multiple_files && n_files > 1))
1522 print_headers = 1;
1524 for (i = 0; i < n_files; i++)
1525 exit_status |= tail_file (&F[i], n_units);
1527 if (forever)
1529 SETVBUF (stdout, NULL, _IONBF, 0);
1530 tail_forever (F, n_files);
1533 if (have_read_stdin && close (0) < 0)
1534 error (EXIT_FAILURE, errno, "-");
1535 if (fclose (stdout) == EOF)
1536 error (EXIT_FAILURE, errno, _("write error"));
1537 exit (exit_status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);