build: update gnulib submodule to latest, for fewer compiler warnings
[coreutils.git] / src / tail.c
blob09afeec9948b5a54564879bce052027869ca07bc
1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989, 90, 91, 1995-2006, 2008-2009 Free Software
3 Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
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>.
25 inotify back-end by Giuseppe Scrivano <gscrivano@gnu.org>. */
27 #include <config.h>
29 #include <stdio.h>
30 #include <assert.h>
31 #include <getopt.h>
32 #include <sys/types.h>
33 #include <signal.h>
35 #include "system.h"
36 #include "argmatch.h"
37 #include "c-strtod.h"
38 #include "error.h"
39 #include "fcntl--.h"
40 #include "isapipe.h"
41 #include "posixver.h"
42 #include "quote.h"
43 #include "safe-read.h"
44 #include "stat-time.h"
45 #include "xfreopen.h"
46 #include "xnanosleep.h"
47 #include "xstrtol.h"
48 #include "xstrtod.h"
50 #if HAVE_INOTIFY
51 # include "hash.h"
52 # include <sys/inotify.h>
53 /* `select' is used by tail_forever_inotify. */
54 # include <sys/select.h>
55 #endif
57 /* The official name of this program (e.g., no `g' prefix). */
58 #define PROGRAM_NAME "tail"
60 #define AUTHORS \
61 proper_name ("Paul Rubin"), \
62 proper_name ("David MacKenzie"), \
63 proper_name ("Ian Lance Taylor"), \
64 proper_name ("Jim Meyering")
66 /* Number of items to tail. */
67 #define DEFAULT_N_LINES 10
69 /* Special values for dump_remainder's N_BYTES parameter. */
70 #define COPY_TO_EOF UINTMAX_MAX
71 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
73 /* FIXME: make Follow_name the default? */
74 #define DEFAULT_FOLLOW_MODE Follow_descriptor
76 enum Follow_mode
78 /* Follow the name of each file: if the file is renamed, try to reopen
79 that name and track the end of the new file if/when it's recreated.
80 This is useful for tracking logs that are occasionally rotated. */
81 Follow_name = 1,
83 /* Follow each descriptor obtained upon opening a file.
84 That means we'll continue to follow the end of a file even after
85 it has been renamed or unlinked. */
86 Follow_descriptor = 2
89 /* The types of files for which tail works. */
90 #define IS_TAILABLE_FILE_TYPE(Mode) \
91 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
93 static char const *const follow_mode_string[] =
95 "descriptor", "name", NULL
98 static enum Follow_mode const follow_mode_map[] =
100 Follow_descriptor, Follow_name,
103 struct File_spec
105 /* The actual file name, or "-" for stdin. */
106 char *name;
108 /* File descriptor on which the file is open; -1 if it's not open. */
109 int fd;
111 /* Attributes of the file the last time we checked. */
112 off_t size;
113 struct timespec mtime;
114 dev_t dev;
115 ino_t ino;
116 mode_t mode;
118 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
119 int blocking;
121 /* The specified name initially referred to a directory or some other
122 type for which tail isn't meaningful. Unlike for a permission problem
123 (tailable, below) once this is set, the name is not checked ever again. */
124 bool ignore;
126 /* See description of DEFAULT_MAX_N_... below. */
127 uintmax_t n_unchanged_stats;
129 /* A file is tailable if it exists, is readable, and is of type
130 IS_TAILABLE_FILE_TYPE. */
131 bool tailable;
133 /* The value of errno seen last time we checked this file. */
134 int errnum;
136 #if HAVE_INOTIFY
137 /* The watch descriptor used by inotify. */
138 int wd;
140 /* The parent directory watch descriptor. It is used only
141 * when Follow_name is used. */
142 int parent_wd;
144 /* Offset in NAME of the basename part. */
145 size_t basename_start;
146 #endif
149 #if HAVE_INOTIFY
150 /* The events mask used with inotify on files. This mask is not used on
151 directories. */
152 const uint32_t inotify_wd_mask = (IN_MODIFY | IN_ATTRIB | IN_DELETE_SELF
153 | IN_MOVE_SELF);
154 #endif
156 /* Keep trying to open a file even if it is inaccessible when tail starts
157 or if it becomes inaccessible later -- useful only with -f. */
158 static bool reopen_inaccessible_files;
160 /* If true, interpret the numeric argument as the number of lines.
161 Otherwise, interpret it as the number of bytes. */
162 static bool count_lines;
164 /* Whether we follow the name of each file or the file descriptor
165 that is initially associated with each name. */
166 static enum Follow_mode follow_mode = Follow_descriptor;
168 /* If true, read from the ends of all specified files until killed. */
169 static bool forever;
171 /* If true, count from start of file instead of end. */
172 static bool from_start;
174 /* If true, print filename headers. */
175 static bool print_headers;
177 /* When to print the filename banners. */
178 enum header_mode
180 multiple_files, always, never
183 /* When tailing a file by name, if there have been this many consecutive
184 iterations for which the file has not changed, then open/fstat
185 the file to determine if that file name is still associated with the
186 same device/inode-number pair as before. This option is meaningful only
187 when following by name. --max-unchanged-stats=N */
188 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
189 static uintmax_t max_n_unchanged_stats_between_opens =
190 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
192 /* The process ID of the process (presumably on the current host)
193 that is writing to all followed files. */
194 static pid_t pid;
196 /* True if we have ever read standard input. */
197 static bool have_read_stdin;
199 /* If nonzero, skip the is-regular-file test used to determine whether
200 to use the lseek optimization. Instead, use the more general (and
201 more expensive) code unconditionally. Intended solely for testing. */
202 static bool presume_input_pipe;
204 /* If nonzero then don't use inotify even if available.
205 Intended solely for testing. */
206 static bool disable_inotify;
208 /* For long options that have no equivalent short option, use a
209 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
210 enum
212 RETRY_OPTION = CHAR_MAX + 1,
213 MAX_UNCHANGED_STATS_OPTION,
214 PID_OPTION,
215 PRESUME_INPUT_PIPE_OPTION,
216 LONG_FOLLOW_OPTION,
217 DISABLE_INOTIFY_OPTION
220 static struct option const long_options[] =
222 {"bytes", required_argument, NULL, 'c'},
223 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
224 {"lines", required_argument, NULL, 'n'},
225 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
226 {"-disable-inotify", no_argument, NULL,
227 DISABLE_INOTIFY_OPTION}, /* do not document */
228 {"pid", required_argument, NULL, PID_OPTION},
229 {"-presume-input-pipe", no_argument, NULL,
230 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
231 {"quiet", no_argument, NULL, 'q'},
232 {"retry", no_argument, NULL, RETRY_OPTION},
233 {"silent", no_argument, NULL, 'q'},
234 {"sleep-interval", required_argument, NULL, 's'},
235 {"verbose", no_argument, NULL, 'v'},
236 {GETOPT_HELP_OPTION_DECL},
237 {GETOPT_VERSION_OPTION_DECL},
238 {NULL, 0, NULL, 0}
241 void
242 usage (int status)
244 if (status != EXIT_SUCCESS)
245 fprintf (stderr, _("Try `%s --help' for more information.\n"),
246 program_name);
247 else
249 printf (_("\
250 Usage: %s [OPTION]... [FILE]...\n\
252 program_name);
253 printf (_("\
254 Print the last %d lines of each FILE to standard output.\n\
255 With more than one FILE, precede each with a header giving the file name.\n\
256 With no FILE, or when FILE is -, read standard input.\n\
258 "), DEFAULT_N_LINES);
259 fputs (_("\
260 Mandatory arguments to long options are mandatory for short options too.\n\
261 "), stdout);
262 fputs (_("\
263 -c, --bytes=K output the last K bytes; alternatively, use -c +K\n\
264 to output bytes starting with the Kth of each file\n\
265 "), stdout);
266 fputs (_("\
267 -f, --follow[={name|descriptor}]\n\
268 output appended data as the file grows;\n\
269 -f, --follow, and --follow=descriptor are\n\
270 equivalent\n\
271 -F same as --follow=name --retry\n\
272 "), stdout);
273 printf (_("\
274 -n, --lines=K output the last K lines, instead of the last %d;\n\
275 or use -n +K to output lines starting with the Kth\n\
276 --max-unchanged-stats=N\n\
277 with --follow=name, reopen a FILE which has not\n\
278 changed size after N (default %d) iterations\n\
279 to see if it has been unlinked or renamed\n\
280 (this is the usual case of rotated log files)\n\
282 DEFAULT_N_LINES,
283 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
285 fputs (_("\
286 --pid=PID with -f, terminate after process ID, PID dies\n\
287 -q, --quiet, --silent never output headers giving file names\n\
288 --retry keep trying to open a file even when it is or\n\
289 becomes inaccessible; useful when following by\n\
290 name, i.e., with --follow=name\n\
291 "), stdout);
292 fputs (_("\
293 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
294 (default 1.0) between iterations\n\
295 -v, --verbose always output headers giving file names\n\
296 "), stdout);
297 fputs (HELP_OPTION_DESCRIPTION, stdout);
298 fputs (VERSION_OPTION_DESCRIPTION, stdout);
299 fputs (_("\
301 If the first character of K (the number of bytes or lines) is a `+',\n\
302 print beginning with the Kth item from the start of each file, otherwise,\n\
303 print the last K items in the file. K may have a multiplier suffix:\n\
304 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
305 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
307 "), stdout);
308 fputs (_("\
309 With --follow (-f), tail defaults to following the file descriptor, which\n\
310 means that even if a tail'ed file is renamed, tail will continue to track\n\
311 its end. \
312 "), stdout);
313 fputs (_("\
314 This default behavior is not desirable when you really want to\n\
315 track the actual name of the file, not the file descriptor (e.g., log\n\
316 rotation). Use --follow=name in that case. That causes tail to track the\n\
317 named file by reopening it periodically to see if it has been removed and\n\
318 recreated by some other program.\n\
319 "), stdout);
320 emit_ancillary_info ();
322 exit (status);
325 static bool
326 valid_file_spec (struct File_spec const *f)
328 /* Exactly one of the following subexpressions must be true. */
329 return ((f->fd == -1) ^ (f->errnum == 0));
332 static char const *
333 pretty_name (struct File_spec const *f)
335 return (STREQ (f->name, "-") ? _("standard input") : f->name);
338 static void
339 xwrite_stdout (char const *buffer, size_t n_bytes)
341 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
342 error (EXIT_FAILURE, errno, _("write error"));
345 /* Record a file F with descriptor FD, size SIZE, status ST, and
346 blocking status BLOCKING. */
348 static void
349 record_open_fd (struct File_spec *f, int fd,
350 off_t size, struct stat const *st,
351 int blocking)
353 f->fd = fd;
354 f->size = size;
355 f->mtime = get_stat_mtime (st);
356 f->dev = st->st_dev;
357 f->ino = st->st_ino;
358 f->mode = st->st_mode;
359 f->blocking = blocking;
360 f->n_unchanged_stats = 0;
361 f->ignore = false;
364 /* Close the file with descriptor FD and name FILENAME. */
366 static void
367 close_fd (int fd, const char *filename)
369 if (fd != -1 && fd != STDIN_FILENO && close (fd))
371 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
375 static void
376 write_header (const char *pretty_filename)
378 static bool first_file = true;
380 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
381 first_file = false;
384 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
385 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
386 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
387 Return the number of bytes read from the file. */
389 static uintmax_t
390 dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
392 uintmax_t n_written;
393 uintmax_t n_remaining = n_bytes;
395 n_written = 0;
396 while (1)
398 char buffer[BUFSIZ];
399 size_t n = MIN (n_remaining, BUFSIZ);
400 size_t bytes_read = safe_read (fd, buffer, n);
401 if (bytes_read == SAFE_READ_ERROR)
403 if (errno != EAGAIN)
404 error (EXIT_FAILURE, errno, _("error reading %s"),
405 quote (pretty_filename));
406 break;
408 if (bytes_read == 0)
409 break;
410 xwrite_stdout (buffer, bytes_read);
411 n_written += bytes_read;
412 if (n_bytes != COPY_TO_EOF)
414 n_remaining -= bytes_read;
415 if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
416 break;
420 return n_written;
423 /* Call lseek with the specified arguments, where file descriptor FD
424 corresponds to the file, FILENAME.
425 Give a diagnostic and exit nonzero if lseek fails.
426 Otherwise, return the resulting offset. */
428 static off_t
429 xlseek (int fd, off_t offset, int whence, char const *filename)
431 off_t new_offset = lseek (fd, offset, whence);
432 char buf[INT_BUFSIZE_BOUND (off_t)];
433 char *s;
435 if (0 <= new_offset)
436 return new_offset;
438 s = offtostr (offset, buf);
439 switch (whence)
441 case SEEK_SET:
442 error (0, errno, _("%s: cannot seek to offset %s"),
443 filename, s);
444 break;
445 case SEEK_CUR:
446 error (0, errno, _("%s: cannot seek to relative offset %s"),
447 filename, s);
448 break;
449 case SEEK_END:
450 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
451 filename, s);
452 break;
453 default:
454 abort ();
457 exit (EXIT_FAILURE);
460 /* Print the last N_LINES lines from the end of file FD.
461 Go backward through the file, reading `BUFSIZ' bytes at a time (except
462 probably the first), until we hit the start of the file or have
463 read NUMBER newlines.
464 START_POS is the starting position of the read pointer for the file
465 associated with FD (may be nonzero).
466 END_POS is the file offset of EOF (one larger than offset of last byte).
467 Return true if successful. */
469 static bool
470 file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
471 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
473 char buffer[BUFSIZ];
474 size_t bytes_read;
475 off_t pos = end_pos;
477 if (n_lines == 0)
478 return true;
480 /* Set `bytes_read' to the size of the last, probably partial, buffer;
481 0 < `bytes_read' <= `BUFSIZ'. */
482 bytes_read = (pos - start_pos) % BUFSIZ;
483 if (bytes_read == 0)
484 bytes_read = BUFSIZ;
485 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
486 reads will be on block boundaries, which might increase efficiency. */
487 pos -= bytes_read;
488 xlseek (fd, pos, SEEK_SET, pretty_filename);
489 bytes_read = safe_read (fd, buffer, bytes_read);
490 if (bytes_read == SAFE_READ_ERROR)
492 error (0, errno, _("error reading %s"), quote (pretty_filename));
493 return false;
495 *read_pos = pos + bytes_read;
497 /* Count the incomplete line on files that don't end with a newline. */
498 if (bytes_read && buffer[bytes_read - 1] != '\n')
499 --n_lines;
503 /* Scan backward, counting the newlines in this bufferfull. */
505 size_t n = bytes_read;
506 while (n)
508 char const *nl;
509 nl = memrchr (buffer, '\n', n);
510 if (nl == NULL)
511 break;
512 n = nl - buffer;
513 if (n_lines-- == 0)
515 /* If this newline isn't the last character in the buffer,
516 output the part that is after it. */
517 if (n != bytes_read - 1)
518 xwrite_stdout (nl + 1, bytes_read - (n + 1));
519 *read_pos += dump_remainder (pretty_filename, fd,
520 end_pos - (pos + bytes_read));
521 return true;
525 /* Not enough newlines in that bufferfull. */
526 if (pos == start_pos)
528 /* Not enough lines in the file; print everything from
529 start_pos to the end. */
530 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
531 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
532 end_pos);
533 return true;
535 pos -= BUFSIZ;
536 xlseek (fd, pos, SEEK_SET, pretty_filename);
538 bytes_read = safe_read (fd, buffer, BUFSIZ);
539 if (bytes_read == SAFE_READ_ERROR)
541 error (0, errno, _("error reading %s"), quote (pretty_filename));
542 return false;
545 *read_pos = pos + bytes_read;
547 while (bytes_read > 0);
549 return true;
552 /* Print the last N_LINES lines from the end of the standard input,
553 open for reading as pipe FD.
554 Buffer the text as a linked list of LBUFFERs, adding them as needed.
555 Return true if successful. */
557 static bool
558 pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
559 uintmax_t *read_pos)
561 struct linebuffer
563 char buffer[BUFSIZ];
564 size_t nbytes;
565 size_t nlines;
566 struct linebuffer *next;
568 typedef struct linebuffer LBUFFER;
569 LBUFFER *first, *last, *tmp;
570 size_t total_lines = 0; /* Total number of newlines in all buffers. */
571 bool ok = true;
572 size_t n_read; /* Size in bytes of most recent read */
574 first = last = xmalloc (sizeof (LBUFFER));
575 first->nbytes = first->nlines = 0;
576 first->next = NULL;
577 tmp = xmalloc (sizeof (LBUFFER));
579 /* Input is always read into a fresh buffer. */
580 while (1)
582 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
583 if (n_read == 0 || n_read == SAFE_READ_ERROR)
584 break;
585 tmp->nbytes = n_read;
586 *read_pos += n_read;
587 tmp->nlines = 0;
588 tmp->next = NULL;
590 /* Count the number of newlines just read. */
592 char const *buffer_end = tmp->buffer + n_read;
593 char const *p = tmp->buffer;
594 while ((p = memchr (p, '\n', buffer_end - p)))
596 ++p;
597 ++tmp->nlines;
600 total_lines += tmp->nlines;
602 /* If there is enough room in the last buffer read, just append the new
603 one to it. This is because when reading from a pipe, `n_read' can
604 often be very small. */
605 if (tmp->nbytes + last->nbytes < BUFSIZ)
607 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
608 last->nbytes += tmp->nbytes;
609 last->nlines += tmp->nlines;
611 else
613 /* If there's not enough room, link the new buffer onto the end of
614 the list, then either free up the oldest buffer for the next
615 read if that would leave enough lines, or else malloc a new one.
616 Some compaction mechanism is possible but probably not
617 worthwhile. */
618 last = last->next = tmp;
619 if (total_lines - first->nlines > n_lines)
621 tmp = first;
622 total_lines -= first->nlines;
623 first = first->next;
625 else
626 tmp = xmalloc (sizeof (LBUFFER));
630 free (tmp);
632 if (n_read == SAFE_READ_ERROR)
634 error (0, errno, _("error reading %s"), quote (pretty_filename));
635 ok = false;
636 goto free_lbuffers;
639 /* If the file is empty, then bail out. */
640 if (last->nbytes == 0)
641 goto free_lbuffers;
643 /* This prevents a core dump when the pipe contains no newlines. */
644 if (n_lines == 0)
645 goto free_lbuffers;
647 /* Count the incomplete line on files that don't end with a newline. */
648 if (last->buffer[last->nbytes - 1] != '\n')
650 ++last->nlines;
651 ++total_lines;
654 /* Run through the list, printing lines. First, skip over unneeded
655 buffers. */
656 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
657 total_lines -= tmp->nlines;
659 /* Find the correct beginning, then print the rest of the file. */
661 char const *beg = tmp->buffer;
662 char const *buffer_end = tmp->buffer + tmp->nbytes;
663 if (total_lines > n_lines)
665 /* Skip `total_lines' - `n_lines' newlines. We made sure that
666 `total_lines' - `n_lines' <= `tmp->nlines'. */
667 size_t j;
668 for (j = total_lines - n_lines; j; --j)
670 beg = memchr (beg, '\n', buffer_end - beg);
671 assert (beg);
672 ++beg;
676 xwrite_stdout (beg, buffer_end - beg);
679 for (tmp = tmp->next; tmp; tmp = tmp->next)
680 xwrite_stdout (tmp->buffer, tmp->nbytes);
682 free_lbuffers:
683 while (first)
685 tmp = first->next;
686 free (first);
687 first = tmp;
689 return ok;
692 /* Print the last N_BYTES characters from the end of pipe FD.
693 This is a stripped down version of pipe_lines.
694 Return true if successful. */
696 static bool
697 pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
698 uintmax_t *read_pos)
700 struct charbuffer
702 char buffer[BUFSIZ];
703 size_t nbytes;
704 struct charbuffer *next;
706 typedef struct charbuffer CBUFFER;
707 CBUFFER *first, *last, *tmp;
708 size_t i; /* Index into buffers. */
709 size_t total_bytes = 0; /* Total characters in all buffers. */
710 bool ok = true;
711 size_t n_read;
713 first = last = xmalloc (sizeof (CBUFFER));
714 first->nbytes = 0;
715 first->next = NULL;
716 tmp = xmalloc (sizeof (CBUFFER));
718 /* Input is always read into a fresh buffer. */
719 while (1)
721 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
722 if (n_read == 0 || n_read == SAFE_READ_ERROR)
723 break;
724 *read_pos += n_read;
725 tmp->nbytes = n_read;
726 tmp->next = NULL;
728 total_bytes += tmp->nbytes;
729 /* If there is enough room in the last buffer read, just append the new
730 one to it. This is because when reading from a pipe, `nbytes' can
731 often be very small. */
732 if (tmp->nbytes + last->nbytes < BUFSIZ)
734 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
735 last->nbytes += tmp->nbytes;
737 else
739 /* If there's not enough room, link the new buffer onto the end of
740 the list, then either free up the oldest buffer for the next
741 read if that would leave enough characters, or else malloc a new
742 one. Some compaction mechanism is possible but probably not
743 worthwhile. */
744 last = last->next = tmp;
745 if (total_bytes - first->nbytes > n_bytes)
747 tmp = first;
748 total_bytes -= first->nbytes;
749 first = first->next;
751 else
753 tmp = xmalloc (sizeof (CBUFFER));
758 free (tmp);
760 if (n_read == SAFE_READ_ERROR)
762 error (0, errno, _("error reading %s"), quote (pretty_filename));
763 ok = false;
764 goto free_cbuffers;
767 /* Run through the list, printing characters. First, skip over unneeded
768 buffers. */
769 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
770 total_bytes -= tmp->nbytes;
772 /* Find the correct beginning, then print the rest of the file.
773 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
774 if (total_bytes > n_bytes)
775 i = total_bytes - n_bytes;
776 else
777 i = 0;
778 xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
780 for (tmp = tmp->next; tmp; tmp = tmp->next)
781 xwrite_stdout (tmp->buffer, tmp->nbytes);
783 free_cbuffers:
784 while (first)
786 tmp = first->next;
787 free (first);
788 first = tmp;
790 return ok;
793 /* Skip N_BYTES characters from the start of pipe FD, and print
794 any extra characters that were read beyond that.
795 Return 1 on error, 0 if ok, -1 if EOF. */
797 static int
798 start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
799 uintmax_t *read_pos)
801 char buffer[BUFSIZ];
803 while (0 < n_bytes)
805 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
806 if (bytes_read == 0)
807 return -1;
808 if (bytes_read == SAFE_READ_ERROR)
810 error (0, errno, _("error reading %s"), quote (pretty_filename));
811 return 1;
813 read_pos += bytes_read;
814 if (bytes_read <= n_bytes)
815 n_bytes -= bytes_read;
816 else
818 size_t n_remaining = bytes_read - n_bytes;
819 if (n_remaining)
820 xwrite_stdout (&buffer[n_bytes], n_remaining);
821 break;
825 return 0;
828 /* Skip N_LINES lines at the start of file or pipe FD, and print
829 any extra characters that were read beyond that.
830 Return 1 on error, 0 if ok, -1 if EOF. */
832 static int
833 start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
834 uintmax_t *read_pos)
836 if (n_lines == 0)
837 return 0;
839 while (1)
841 char buffer[BUFSIZ];
842 char *p = buffer;
843 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
844 char *buffer_end = buffer + bytes_read;
845 if (bytes_read == 0) /* EOF */
846 return -1;
847 if (bytes_read == SAFE_READ_ERROR) /* error */
849 error (0, errno, _("error reading %s"), quote (pretty_filename));
850 return 1;
853 *read_pos += bytes_read;
855 while ((p = memchr (p, '\n', buffer_end - p)))
857 ++p;
858 if (--n_lines == 0)
860 if (p < buffer_end)
861 xwrite_stdout (p, buffer_end - p);
862 return 0;
868 /* FIXME: describe */
870 static void
871 recheck (struct File_spec *f, bool blocking)
873 /* open/fstat the file and announce if dev/ino have changed */
874 struct stat new_stats;
875 bool ok = true;
876 bool is_stdin = (STREQ (f->name, "-"));
877 bool was_tailable = f->tailable;
878 int prev_errnum = f->errnum;
879 bool new_file;
880 int fd = (is_stdin
881 ? STDIN_FILENO
882 : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
884 assert (valid_file_spec (f));
886 /* If the open fails because the file doesn't exist,
887 then mark the file as not tailable. */
888 f->tailable = !(reopen_inaccessible_files && fd == -1);
890 if (fd == -1 || fstat (fd, &new_stats) < 0)
892 ok = false;
893 f->errnum = errno;
894 if (!f->tailable)
896 if (was_tailable)
898 /* FIXME-maybe: detect the case in which the file first becomes
899 unreadable (perms), and later becomes readable again and can
900 be seen to be the same file (dev/ino). Otherwise, tail prints
901 the entire contents of the file when it becomes readable. */
902 error (0, f->errnum, _("%s has become inaccessible"),
903 quote (pretty_name (f)));
905 else
907 /* say nothing... it's still not tailable */
910 else if (prev_errnum != errno)
912 error (0, errno, "%s", pretty_name (f));
915 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
917 ok = false;
918 f->errnum = -1;
919 error (0, 0, _("%s has been replaced with an untailable file;\
920 giving up on this name"),
921 quote (pretty_name (f)));
922 f->ignore = true;
924 else
926 f->errnum = 0;
929 new_file = false;
930 if (!ok)
932 close_fd (fd, pretty_name (f));
933 close_fd (f->fd, pretty_name (f));
934 f->fd = -1;
936 else if (prev_errnum && prev_errnum != ENOENT)
938 new_file = true;
939 assert (f->fd == -1);
940 error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
942 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
944 new_file = true;
945 if (f->fd == -1)
947 error (0, 0,
948 _("%s has appeared; following end of new file"),
949 quote (pretty_name (f)));
951 else
953 /* Close the old one. */
954 close_fd (f->fd, pretty_name (f));
956 /* File has been replaced (e.g., via log rotation) --
957 tail the new one. */
958 error (0, 0,
959 _("%s has been replaced; following end of new file"),
960 quote (pretty_name (f)));
963 else
965 if (f->fd == -1)
967 /* This happens when one iteration finds the file missing,
968 then the preceding <dev,inode> pair is reused as the
969 file is recreated. */
970 new_file = true;
972 else
974 close_fd (fd, pretty_name (f));
978 if (new_file)
980 /* Start at the beginning of the file. */
981 record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
982 xlseek (fd, 0, SEEK_SET, pretty_name (f));
986 /* Return true if any of the N_FILES files in F are live, i.e., have
987 open file descriptors. */
989 static bool
990 any_live_files (const struct File_spec *f, size_t n_files)
992 size_t i;
994 for (i = 0; i < n_files; i++)
995 if (0 <= f[i].fd)
996 return true;
997 return false;
1000 /* Tail N_FILES files forever, or until killed.
1001 The pertinent information for each file is stored in an entry of F.
1002 Loop over each of them, doing an fstat to see if they have changed size,
1003 and an occasional open/fstat to see if any dev/ino pair has changed.
1004 If none of them have changed size in one iteration, sleep for a
1005 while and try again. Continue until the user interrupts us. */
1007 static void
1008 tail_forever (struct File_spec *f, size_t n_files, double sleep_interval)
1010 /* Use blocking I/O as an optimization, when it's easy. */
1011 bool blocking = (pid == 0 && follow_mode == Follow_descriptor
1012 && n_files == 1 && ! S_ISREG (f[0].mode));
1013 size_t last;
1014 bool writer_is_dead = false;
1016 last = n_files - 1;
1018 while (1)
1020 size_t i;
1021 bool any_input = false;
1023 for (i = 0; i < n_files; i++)
1025 int fd;
1026 char const *name;
1027 mode_t mode;
1028 struct stat stats;
1029 uintmax_t bytes_read;
1031 if (f[i].ignore)
1032 continue;
1034 if (f[i].fd < 0)
1036 recheck (&f[i], blocking);
1037 continue;
1040 fd = f[i].fd;
1041 name = pretty_name (&f[i]);
1042 mode = f[i].mode;
1044 if (f[i].blocking != blocking)
1046 int old_flags = fcntl (fd, F_GETFL);
1047 int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
1048 if (old_flags < 0
1049 || (new_flags != old_flags
1050 && fcntl (fd, F_SETFL, new_flags) == -1))
1052 /* Don't update f[i].blocking if fcntl fails. */
1053 if (S_ISREG (f[i].mode) && errno == EPERM)
1055 /* This happens when using tail -f on a file with
1056 the append-only attribute. */
1058 else
1059 error (EXIT_FAILURE, errno,
1060 _("%s: cannot change nonblocking mode"), name);
1062 else
1063 f[i].blocking = blocking;
1066 if (!f[i].blocking)
1068 if (fstat (fd, &stats) != 0)
1070 f[i].fd = -1;
1071 f[i].errnum = errno;
1072 error (0, errno, "%s", name);
1073 continue;
1076 if (f[i].mode == stats.st_mode
1077 && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
1078 && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
1080 if ((max_n_unchanged_stats_between_opens
1081 <= f[i].n_unchanged_stats++)
1082 && follow_mode == Follow_name)
1084 recheck (&f[i], f[i].blocking);
1085 f[i].n_unchanged_stats = 0;
1087 continue;
1090 /* This file has changed. Print out what we can, and
1091 then keep looping. */
1093 f[i].mtime = get_stat_mtime (&stats);
1094 f[i].mode = stats.st_mode;
1096 /* reset counter */
1097 f[i].n_unchanged_stats = 0;
1099 if (S_ISREG (mode) && stats.st_size < f[i].size)
1101 error (0, 0, _("%s: file truncated"), name);
1102 last = i;
1103 xlseek (fd, stats.st_size, SEEK_SET, name);
1104 f[i].size = stats.st_size;
1105 continue;
1108 if (i != last)
1110 if (print_headers)
1111 write_header (name);
1112 last = i;
1116 bytes_read = dump_remainder (name, fd,
1117 (f[i].blocking
1118 ? COPY_A_BUFFER : COPY_TO_EOF));
1119 any_input |= (bytes_read != 0);
1120 f[i].size += bytes_read;
1123 if (! any_live_files (f, n_files) && ! reopen_inaccessible_files)
1125 error (0, 0, _("no files remaining"));
1126 break;
1129 if ((!any_input || blocking) && fflush (stdout) != 0)
1130 error (EXIT_FAILURE, errno, _("write error"));
1132 /* If nothing was read, sleep and/or check for dead writers. */
1133 if (!any_input)
1135 if (writer_is_dead)
1136 break;
1138 /* Once the writer is dead, read the files once more to
1139 avoid a race condition. */
1140 writer_is_dead = (pid != 0
1141 && kill (pid, 0) != 0
1142 /* Handle the case in which you cannot send a
1143 signal to the writer, so kill fails and sets
1144 errno to EPERM. */
1145 && errno != EPERM);
1147 if (!writer_is_dead && xnanosleep (sleep_interval))
1148 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1154 #if HAVE_INOTIFY
1156 static size_t
1157 wd_hasher (const void *entry, size_t tabsize)
1159 const struct File_spec *spec = entry;
1160 return spec->wd % tabsize;
1163 static bool
1164 wd_comparator (const void *e1, const void *e2)
1166 const struct File_spec *spec1 = e1;
1167 const struct File_spec *spec2 = e2;
1168 return spec1->wd == spec2->wd;
1171 /* Helper function used by `tail_forever_inotify'. */
1173 static void
1174 check_fspec (struct File_spec *fspec, int wd, int *prev_wd)
1176 struct stat stats;
1177 char const *name = pretty_name (fspec);
1179 if (fstat (fspec->fd, &stats) != 0)
1181 close_fd (fspec->fd, name);
1182 fspec->fd = -1;
1183 fspec->errnum = errno;
1184 return;
1187 if (S_ISREG (fspec->mode) && stats.st_size < fspec->size)
1189 error (0, 0, _("%s: file truncated"), name);
1190 *prev_wd = wd;
1191 xlseek (fspec->fd, stats.st_size, SEEK_SET, name);
1192 fspec->size = stats.st_size;
1194 else if (S_ISREG (fspec->mode) && stats.st_size == fspec->size
1195 && timespec_cmp (fspec->mtime, get_stat_mtime (&stats)) == 0)
1196 return;
1198 if (wd != *prev_wd)
1200 if (print_headers)
1201 write_header (name);
1202 *prev_wd = wd;
1205 uintmax_t bytes_read = dump_remainder (name, fspec->fd, COPY_TO_EOF);
1206 fspec->size += bytes_read;
1208 if (fflush (stdout) != 0)
1209 error (EXIT_FAILURE, errno, _("write error"));
1212 /* Tail N_FILES files forever, or until killed.
1213 Check modifications using the inotify events system. */
1215 static void
1216 tail_forever_inotify (int wd, struct File_spec *f, size_t n_files,
1217 double sleep_interval)
1219 size_t i;
1220 unsigned int max_realloc = 3;
1221 Hash_table *wd_table;
1223 bool found_watchable = false;
1224 bool writer_is_dead = false;
1225 int prev_wd;
1226 size_t evlen = 0;
1227 char *evbuf;
1228 size_t evbuf_off = 0;
1229 size_t len = 0;
1231 wd_table = hash_initialize (n_files, NULL, wd_hasher, wd_comparator, NULL);
1232 if (! wd_table)
1233 xalloc_die ();
1235 /* Add an inotify watch for each watched file. If -F is specified then watch
1236 its parent directory too, in this way when they re-appear we can add them
1237 again to the watch list. */
1238 for (i = 0; i < n_files; i++)
1240 if (!f[i].ignore)
1242 size_t fnlen = strlen (f[i].name);
1243 if (evlen < fnlen)
1244 evlen = fnlen;
1246 f[i].wd = -1;
1248 if (follow_mode == Follow_name)
1250 size_t dirlen = dir_len (f[i].name);
1251 char prev = f[i].name[dirlen];
1252 f[i].basename_start = last_component (f[i].name) - f[i].name;
1254 f[i].name[dirlen] = '\0';
1256 /* It's fine to add the same directory more than once.
1257 In that case the same watch descriptor is returned. */
1258 f[i].parent_wd = inotify_add_watch (wd, dirlen ? f[i].name : ".",
1259 (IN_CREATE | IN_MOVED_TO
1260 | IN_ATTRIB));
1262 f[i].name[dirlen] = prev;
1264 if (f[i].parent_wd < 0)
1266 error (0, errno, _("cannot watch parent directory of %s"),
1267 quote (f[i].name));
1268 continue;
1272 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1274 if (f[i].wd < 0)
1276 if (errno != f[i].errnum)
1277 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1278 continue;
1281 if (hash_insert (wd_table, &(f[i])) == NULL)
1282 xalloc_die ();
1284 found_watchable = true;
1288 if (follow_mode == Follow_descriptor && !found_watchable)
1289 return;
1291 prev_wd = f[n_files - 1].wd;
1293 /* Check files again. New data can be available since last time we checked
1294 and before they are watched by inotify. */
1295 for (i = 0; i < n_files; i++)
1297 if (!f[i].ignore)
1298 check_fspec (&f[i], f[i].wd, &prev_wd);
1301 evlen += sizeof (struct inotify_event) + 1;
1302 evbuf = xmalloc (evlen);
1304 /* Wait for inotify events and handle them. Events on directories make sure
1305 that watched files can be re-added when -F is used.
1306 This loop sleeps on the `safe_read' call until a new event is notified. */
1307 while (1)
1309 struct File_spec *fspec;
1310 struct inotify_event *ev;
1312 /* When watching a PID, ensure that a read from WD will not block
1313 indefinetely. */
1314 if (pid)
1316 if (writer_is_dead)
1317 exit (EXIT_SUCCESS);
1319 writer_is_dead = (kill (pid, 0) != 0 && errno != EPERM);
1321 struct timeval delay; /* how long to wait for file changes. */
1322 if (writer_is_dead)
1323 delay.tv_sec = delay.tv_usec = 0;
1324 else
1326 delay.tv_sec = (time_t) sleep_interval;
1327 delay.tv_usec = 1000000 * (sleep_interval - delay.tv_sec);
1330 fd_set rfd;
1331 FD_ZERO (&rfd);
1332 FD_SET (wd, &rfd);
1334 int file_change = select (wd + 1, &rfd, NULL, NULL, &delay);
1336 if (file_change == 0)
1337 continue;
1338 else if (file_change == -1)
1339 error (EXIT_FAILURE, errno, _("error monitoring inotify event"));
1342 if (len <= evbuf_off)
1344 len = safe_read (wd, evbuf, evlen);
1345 evbuf_off = 0;
1347 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1348 is too small. */
1349 if ((len == 0 || (len == SAFE_READ_ERROR && errno == EINVAL))
1350 && max_realloc--)
1352 len = 0;
1353 evlen *= 2;
1354 evbuf = xrealloc (evbuf, evlen);
1355 continue;
1358 if (len == 0 || len == SAFE_READ_ERROR)
1359 error (EXIT_FAILURE, errno, _("error reading inotify event"));
1362 ev = (struct inotify_event *) (evbuf + evbuf_off);
1363 evbuf_off += sizeof (*ev) + ev->len;
1365 if (ev->len)
1367 for (i = 0; i < n_files; i++)
1369 /* With N=hundreds of frequently-changing files, this O(N^2)
1370 process might be a problem. FIXME: use a hash table? */
1371 if (f[i].parent_wd == ev->wd
1372 && STREQ (ev->name, f[i].name + f[i].basename_start))
1373 break;
1376 /* It is not a watched file. */
1377 if (i == n_files)
1378 continue;
1380 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1382 if (f[i].wd < 0)
1384 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1385 continue;
1388 fspec = &(f[i]);
1389 if (hash_insert (wd_table, fspec) == NULL)
1390 xalloc_die ();
1392 if (follow_mode == Follow_name)
1393 recheck (&(f[i]), false);
1395 else
1397 struct File_spec key;
1398 key.wd = ev->wd;
1399 fspec = hash_lookup (wd_table, &key);
1402 if (! fspec)
1403 continue;
1405 if (ev->mask & (IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF))
1407 if (ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF))
1409 inotify_rm_watch (wd, f[i].wd);
1410 hash_delete (wd_table, &(f[i]));
1412 if (follow_mode == Follow_name)
1413 recheck (fspec, false);
1415 continue;
1417 check_fspec (fspec, ev->wd, &prev_wd);
1420 #endif
1422 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1423 Return true if successful. */
1425 static bool
1426 tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1427 uintmax_t *read_pos)
1429 struct stat stats;
1431 if (fstat (fd, &stats))
1433 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1434 return false;
1437 if (from_start)
1439 if ( ! presume_input_pipe
1440 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1442 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1443 *read_pos += n_bytes;
1445 else
1447 int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
1448 if (t)
1449 return t < 0;
1451 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1453 else
1455 if ( ! presume_input_pipe
1456 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1458 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1459 off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename);
1460 off_t diff = end_pos - current_pos;
1461 /* Be careful here. The current position may actually be
1462 beyond the end of the file. */
1463 off_t bytes_remaining = diff < 0 ? 0 : diff;
1464 off_t nb = n_bytes;
1466 if (bytes_remaining <= nb)
1468 /* From the current position to end of file, there are no
1469 more bytes than have been requested. So reposition the
1470 file pointer to the incoming current position and print
1471 everything after that. */
1472 *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1474 else
1476 /* There are more bytes remaining than were requested.
1477 Back up. */
1478 *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename);
1480 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1482 else
1483 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1485 return true;
1488 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1489 Return true if successful. */
1491 static bool
1492 tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1493 uintmax_t *read_pos)
1495 struct stat stats;
1497 if (fstat (fd, &stats))
1499 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1500 return false;
1503 if (from_start)
1505 int t = start_lines (pretty_filename, fd, n_lines, read_pos);
1506 if (t)
1507 return t < 0;
1508 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1510 else
1512 off_t start_pos = -1;
1513 off_t end_pos;
1515 /* Use file_lines only if FD refers to a regular file for
1516 which lseek (... SEEK_END) works. */
1517 if ( ! presume_input_pipe
1518 && S_ISREG (stats.st_mode)
1519 && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
1520 && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
1522 *read_pos = end_pos;
1523 if (end_pos != 0
1524 && ! file_lines (pretty_filename, fd, n_lines,
1525 start_pos, end_pos, read_pos))
1526 return false;
1528 else
1530 /* Under very unlikely circumstances, it is possible to reach
1531 this point after positioning the file pointer to end of file
1532 via the `lseek (...SEEK_END)' above. In that case, reposition
1533 the file pointer back to start_pos before calling pipe_lines. */
1534 if (start_pos != -1)
1535 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1537 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1540 return true;
1543 /* Display the last N_UNITS units of file FILENAME, open for reading
1544 via FD. Set *READ_POS to the position of the input stream pointer.
1545 *READ_POS is usually the number of bytes read and corresponds to an
1546 offset from the beginning of a file. However, it may be larger than
1547 OFF_T_MAX (as for an input pipe), and may also be larger than the
1548 number of bytes read (when an input pointer is initially not at
1549 beginning of file), and may be far greater than the number of bytes
1550 actually read for an input file that is seekable.
1551 Return true if successful. */
1553 static bool
1554 tail (const char *filename, int fd, uintmax_t n_units,
1555 uintmax_t *read_pos)
1557 *read_pos = 0;
1558 if (count_lines)
1559 return tail_lines (filename, fd, n_units, read_pos);
1560 else
1561 return tail_bytes (filename, fd, n_units, read_pos);
1564 /* Display the last N_UNITS units of the file described by F.
1565 Return true if successful. */
1567 static bool
1568 tail_file (struct File_spec *f, uintmax_t n_units)
1570 int fd;
1571 bool ok;
1573 bool is_stdin = (STREQ (f->name, "-"));
1575 if (is_stdin)
1577 have_read_stdin = true;
1578 fd = STDIN_FILENO;
1579 if (O_BINARY && ! isatty (STDIN_FILENO))
1580 xfreopen (NULL, "rb", stdin);
1582 else
1583 fd = open (f->name, O_RDONLY | O_BINARY);
1585 f->tailable = !(reopen_inaccessible_files && fd == -1);
1587 if (fd == -1)
1589 if (forever)
1591 f->fd = -1;
1592 f->errnum = errno;
1593 f->ignore = false;
1594 f->ino = 0;
1595 f->dev = 0;
1597 error (0, errno, _("cannot open %s for reading"),
1598 quote (pretty_name (f)));
1599 ok = false;
1601 else
1603 uintmax_t read_pos;
1605 if (print_headers)
1606 write_header (pretty_name (f));
1607 ok = tail (pretty_name (f), fd, n_units, &read_pos);
1608 if (forever)
1610 struct stat stats;
1612 #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
1613 /* Before the tail function provided `read_pos', there was
1614 a race condition described in the URL below. This sleep
1615 call made the window big enough to exercise the problem. */
1616 sleep (1);
1617 #endif
1618 f->errnum = ok - 1;
1619 if (fstat (fd, &stats) < 0)
1621 ok = false;
1622 f->errnum = errno;
1623 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1625 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1627 error (0, 0, _("%s: cannot follow end of this type of file;\
1628 giving up on this name"),
1629 pretty_name (f));
1630 ok = false;
1631 f->errnum = -1;
1632 f->ignore = true;
1635 if (!ok)
1637 close_fd (fd, pretty_name (f));
1638 f->fd = -1;
1640 else
1642 /* Note: we must use read_pos here, not stats.st_size,
1643 to avoid a race condition described by Ken Raeburn:
1644 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1645 record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
1648 else
1650 if (!is_stdin && close (fd))
1652 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1653 ok = false;
1658 return ok;
1661 /* If obsolete usage is allowed, and the command line arguments are of
1662 the obsolete form and the option string is well-formed, set
1663 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1664 return true. If the command line arguments are obviously incorrect
1665 (e.g., because obsolete usage is not allowed and the arguments are
1666 incorrect for non-obsolete usage), report an error and exit.
1667 Otherwise, return false and don't modify any parameter or global
1668 variable. */
1670 static bool
1671 parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
1673 const char *p;
1674 const char *n_string;
1675 const char *n_string_end;
1676 bool obsolete_usage;
1677 int default_count = DEFAULT_N_LINES;
1678 bool t_from_start;
1679 bool t_count_lines = true;
1680 bool t_forever = false;
1682 /* With the obsolete form, there is one option string and at most
1683 one file argument. Watch out for "-" and "--", though. */
1684 if (! (argc == 2
1685 || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
1686 || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
1687 return false;
1689 obsolete_usage = (posix2_version () < 200112);
1690 p = argv[1];
1692 switch (*p++)
1694 default:
1695 return false;
1697 case '+':
1698 /* Leading "+" is a file name in the non-obsolete form. */
1699 if (!obsolete_usage)
1700 return false;
1702 t_from_start = true;
1703 break;
1705 case '-':
1706 /* In the non-obsolete form, "-" is standard input and "-c"
1707 requires an option-argument. The obsolete multidigit options
1708 are supported as a GNU extension even when conforming to
1709 POSIX 1003.1-2001, so don't complain about them. */
1710 if (!obsolete_usage && !p[p[0] == 'c'])
1711 return false;
1713 t_from_start = false;
1714 break;
1717 n_string = p;
1718 while (ISDIGIT (*p))
1719 p++;
1720 n_string_end = p;
1722 switch (*p)
1724 case 'b': default_count *= 512; /* Fall through. */
1725 case 'c': t_count_lines = false; /* Fall through. */
1726 case 'l': p++; break;
1729 if (*p == 'f')
1731 t_forever = true;
1732 ++p;
1735 if (*p)
1736 return false;
1738 if (n_string == n_string_end)
1739 *n_units = default_count;
1740 else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
1741 & ~LONGINT_INVALID_SUFFIX_CHAR)
1742 != LONGINT_OK)
1743 error (EXIT_FAILURE, 0, _("number in %s is too large"), quote (argv[1]));
1745 /* Set globals. */
1746 from_start = t_from_start;
1747 count_lines = t_count_lines;
1748 forever = t_forever;
1750 return true;
1753 static void
1754 parse_options (int argc, char **argv,
1755 uintmax_t *n_units, enum header_mode *header_mode,
1756 double *sleep_interval)
1758 int c;
1760 while ((c = getopt_long (argc, argv, "c:n:fFqs:v0123456789",
1761 long_options, NULL))
1762 != -1)
1764 switch (c)
1766 case 'F':
1767 forever = true;
1768 follow_mode = Follow_name;
1769 reopen_inaccessible_files = true;
1770 break;
1772 case 'c':
1773 case 'n':
1774 count_lines = (c == 'n');
1775 if (*optarg == '+')
1776 from_start = true;
1777 else if (*optarg == '-')
1778 ++optarg;
1781 strtol_error s_err;
1782 s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkKmMGTPEZY0");
1783 if (s_err != LONGINT_OK)
1785 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1786 (c == 'n'
1787 ? _("invalid number of lines")
1788 : _("invalid number of bytes")));
1791 break;
1793 case 'f':
1794 case LONG_FOLLOW_OPTION:
1795 forever = true;
1796 if (optarg == NULL)
1797 follow_mode = DEFAULT_FOLLOW_MODE;
1798 else
1799 follow_mode = XARGMATCH ("--follow", optarg,
1800 follow_mode_string, follow_mode_map);
1801 break;
1803 case RETRY_OPTION:
1804 reopen_inaccessible_files = true;
1805 break;
1807 case MAX_UNCHANGED_STATS_OPTION:
1808 /* --max-unchanged-stats=N */
1809 if (xstrtoumax (optarg, NULL, 10,
1810 &max_n_unchanged_stats_between_opens,
1812 != LONGINT_OK)
1814 error (EXIT_FAILURE, 0,
1815 _("%s: invalid maximum number of unchanged stats between opens"),
1816 optarg);
1818 break;
1820 case DISABLE_INOTIFY_OPTION:
1821 disable_inotify = true;
1822 break;
1824 case PID_OPTION:
1826 strtol_error s_err;
1827 unsigned long int tmp_ulong;
1828 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1829 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1831 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1833 pid = tmp_ulong;
1835 break;
1837 case PRESUME_INPUT_PIPE_OPTION:
1838 presume_input_pipe = true;
1839 break;
1841 case 'q':
1842 *header_mode = never;
1843 break;
1845 case 's':
1847 double s;
1848 if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
1849 error (EXIT_FAILURE, 0,
1850 _("%s: invalid number of seconds"), optarg);
1851 *sleep_interval = s;
1853 break;
1855 case 'v':
1856 *header_mode = always;
1857 break;
1859 case_GETOPT_HELP_CHAR;
1861 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1863 case '0': case '1': case '2': case '3': case '4':
1864 case '5': case '6': case '7': case '8': case '9':
1865 error (EXIT_FAILURE, 0,
1866 _("option used in invalid context -- %c"), c);
1868 default:
1869 usage (EXIT_FAILURE);
1873 if (reopen_inaccessible_files && follow_mode != Follow_name)
1874 error (0, 0, _("warning: --retry is useful mainly when following by name"));
1876 if (pid && !forever)
1877 error (0, 0,
1878 _("warning: PID ignored; --pid=PID is useful only when following"));
1879 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
1881 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1882 pid = 0;
1887 main (int argc, char **argv)
1889 enum header_mode header_mode = multiple_files;
1890 bool ok = true;
1891 /* If from_start, the number of items to skip before printing; otherwise,
1892 the number of items at the end of the file to print. Although the type
1893 is signed, the value is never negative. */
1894 uintmax_t n_units = DEFAULT_N_LINES;
1895 size_t n_files;
1896 char **file;
1897 struct File_spec *F;
1898 size_t i;
1899 bool obsolete_option;
1901 /* The number of seconds to sleep between iterations.
1902 During one iteration, every file name or descriptor is checked to
1903 see if it has changed. */
1904 double sleep_interval = 1.0;
1906 initialize_main (&argc, &argv);
1907 set_program_name (argv[0]);
1908 setlocale (LC_ALL, "");
1909 bindtextdomain (PACKAGE, LOCALEDIR);
1910 textdomain (PACKAGE);
1912 atexit (close_stdout);
1914 have_read_stdin = false;
1916 count_lines = true;
1917 forever = from_start = print_headers = false;
1918 obsolete_option = parse_obsolete_option (argc, argv, &n_units);
1919 argc -= obsolete_option;
1920 argv += obsolete_option;
1921 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
1923 /* To start printing with item N_UNITS from the start of the file, skip
1924 N_UNITS - 1 items. `tail -n +0' is actually meaningless, but for Unix
1925 compatibility it's treated the same as `tail -n +1'. */
1926 if (from_start)
1928 if (n_units)
1929 --n_units;
1932 if (optind < argc)
1934 n_files = argc - optind;
1935 file = argv + optind;
1937 else
1939 static char *dummy_stdin = (char *) "-";
1940 n_files = 1;
1941 file = &dummy_stdin;
1945 bool found_hyphen = false;
1947 for (i = 0; i < n_files; i++)
1948 if (STREQ (file[i], "-"))
1949 found_hyphen = true;
1951 /* When following by name, there must be a name. */
1952 if (found_hyphen && follow_mode == Follow_name)
1953 error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quote ("-"));
1955 /* When following forever, warn if any file is `-'.
1956 This is only a warning, since tail's output (before a failing seek,
1957 and that from any non-stdin files) might still be useful. */
1958 if (forever && found_hyphen && isatty (STDIN_FILENO))
1959 error (0, 0, _("warning: following standard input"
1960 " indefinitely is ineffective"));
1963 F = xnmalloc (n_files, sizeof *F);
1964 for (i = 0; i < n_files; i++)
1965 F[i].name = file[i];
1967 if (header_mode == always
1968 || (header_mode == multiple_files && n_files > 1))
1969 print_headers = true;
1971 if (O_BINARY && ! isatty (STDOUT_FILENO))
1972 xfreopen (NULL, "wb", stdout);
1974 for (i = 0; i < n_files; i++)
1975 ok &= tail_file (&F[i], n_units);
1977 /* When there is no FILE operand and stdin is a pipe or FIFO
1978 POSIX requires that tail ignore the -f option.
1979 Since we allow multiple FILE operands, we extend that to say:
1980 ignore any "-" operand that corresponds to a pipe or FIFO. */
1981 size_t n_viable = 0;
1982 for (i = 0; i < n_files; i++)
1984 bool is_a_fifo_or_pipe =
1985 (STREQ (F[i].name, "-")
1986 && !F[i].ignore
1987 && 0 <= F[i].fd
1988 && (S_ISFIFO (F[i].mode)
1989 || (HAVE_FIFO_PIPES != 1 && isapipe (F[i].fd))));
1990 if (is_a_fifo_or_pipe)
1991 F[i].ignore = true;
1992 else
1993 ++n_viable;
1996 if (forever && n_viable)
1998 #if HAVE_INOTIFY
1999 /* If the user specifies stdin via a command line argument of "-",
2000 or implicitly by providing no arguments, we won't use inotify.
2001 Technically, on systems with a working /dev/stdin, we *could*,
2002 but would it be worth it? Verifying that it's a real device
2003 and hooked up to stdin is not trivial, while reverting to
2004 non-inotify-based tail_forever is easy and portable. */
2005 bool stdin_cmdline_arg = false;
2007 for (i = 0; i < n_files; i++)
2008 if (!F[i].ignore && STREQ (F[i].name, "-"))
2009 stdin_cmdline_arg = true;
2011 if (!disable_inotify && !stdin_cmdline_arg)
2013 int wd = inotify_init ();
2014 if (wd < 0)
2015 error (0, errno, _("inotify cannot be used, reverting to polling"));
2016 else
2018 /* Flush any output from tail_file, now, since
2019 tail_forever_inotify flushes only after writing,
2020 not before reading. */
2021 if (fflush (stdout) != 0)
2022 error (EXIT_FAILURE, errno, _("write error"));
2024 tail_forever_inotify (wd, F, n_files, sleep_interval);
2026 /* The only way the above returns is upon failure. */
2027 exit (EXIT_FAILURE);
2030 #endif
2031 tail_forever (F, n_files, sleep_interval);
2034 if (have_read_stdin && close (STDIN_FILENO) < 0)
2035 error (EXIT_FAILURE, errno, "-");
2036 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);