maint: update a couple of NEWS items for the pending release
[coreutils/ericb.git] / src / tail.c
blob9e95dee7e64bea36553ffeb704f8e3618abd6efe
1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989-1991, 1995-2006, 2008-2010 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 3 of the License, or
7 (at your option) 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, see <http://www.gnu.org/licenses/>. */
17 /* Can display any amount of data, unlike the Unix version, which uses
18 a fixed size buffer and therefore can only deliver a limited number
19 of lines.
21 Original version by Paul Rubin <phr@ocf.berkeley.edu>.
22 Extensions by David MacKenzie <djm@gnu.ai.mit.edu>.
23 tail -f for multiple files by Ian Lance Taylor <ian@airs.com>.
24 inotify back-end by Giuseppe Scrivano <gscrivano@gnu.org>. */
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 "c-strtod.h"
37 #include "error.h"
38 #include "fcntl--.h"
39 #include "isapipe.h"
40 #include "posixver.h"
41 #include "quote.h"
42 #include "safe-read.h"
43 #include "stat-time.h"
44 #include "xfreopen.h"
45 #include "xnanosleep.h"
46 #include "xstrtol.h"
47 #include "xstrtod.h"
49 #if HAVE_INOTIFY
50 # include "hash.h"
51 # include <sys/inotify.h>
52 /* `select' is used by tail_forever_inotify. */
53 # include <sys/select.h>
55 /* inotify needs to know if a file is local. */
56 # include "fs.h"
57 # if HAVE_SYS_STATFS_H
58 # include <sys/statfs.h>
59 # elif HAVE_SYS_VFS_H
60 # include <sys/vfs.h>
61 # endif
62 #endif
64 /* The official name of this program (e.g., no `g' prefix). */
65 #define PROGRAM_NAME "tail"
67 #define AUTHORS \
68 proper_name ("Paul Rubin"), \
69 proper_name ("David MacKenzie"), \
70 proper_name ("Ian Lance Taylor"), \
71 proper_name ("Jim Meyering")
73 /* Number of items to tail. */
74 #define DEFAULT_N_LINES 10
76 /* Special values for dump_remainder's N_BYTES parameter. */
77 #define COPY_TO_EOF UINTMAX_MAX
78 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
80 /* FIXME: make Follow_name the default? */
81 #define DEFAULT_FOLLOW_MODE Follow_descriptor
83 enum Follow_mode
85 /* Follow the name of each file: if the file is renamed, try to reopen
86 that name and track the end of the new file if/when it's recreated.
87 This is useful for tracking logs that are occasionally rotated. */
88 Follow_name = 1,
90 /* Follow each descriptor obtained upon opening a file.
91 That means we'll continue to follow the end of a file even after
92 it has been renamed or unlinked. */
93 Follow_descriptor = 2
96 /* The types of files for which tail works. */
97 #define IS_TAILABLE_FILE_TYPE(Mode) \
98 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
100 static char const *const follow_mode_string[] =
102 "descriptor", "name", NULL
105 static enum Follow_mode const follow_mode_map[] =
107 Follow_descriptor, Follow_name,
110 struct File_spec
112 /* The actual file name, or "-" for stdin. */
113 char *name;
115 /* Attributes of the file the last time we checked. */
116 off_t size;
117 struct timespec mtime;
118 dev_t dev;
119 ino_t ino;
120 mode_t mode;
122 /* The specified name initially referred to a directory or some other
123 type for which tail isn't meaningful. Unlike for a permission problem
124 (tailable, below) once this is set, the name is not checked ever again. */
125 bool ignore;
127 /* See the description of fremote. */
128 bool remote;
130 /* A file is tailable if it exists, is readable, and is of type
131 IS_TAILABLE_FILE_TYPE. */
132 bool tailable;
134 /* File descriptor on which the file is open; -1 if it's not open. */
135 int fd;
137 /* The value of errno seen last time we checked this file. */
138 int errnum;
140 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
141 int blocking;
143 #if HAVE_INOTIFY
144 /* The watch descriptor used by inotify. */
145 int wd;
147 /* The parent directory watch descriptor. It is used only
148 * when Follow_name is used. */
149 int parent_wd;
151 /* Offset in NAME of the basename part. */
152 size_t basename_start;
153 #endif
155 /* See description of DEFAULT_MAX_N_... below. */
156 uintmax_t n_unchanged_stats;
159 #if HAVE_INOTIFY
160 /* The events mask used with inotify on files. This mask is not used on
161 directories. */
162 const uint32_t inotify_wd_mask = (IN_MODIFY | IN_ATTRIB | IN_DELETE_SELF
163 | IN_MOVE_SELF);
164 #endif
166 /* Keep trying to open a file even if it is inaccessible when tail starts
167 or if it becomes inaccessible later -- useful only with -f. */
168 static bool reopen_inaccessible_files;
170 /* If true, interpret the numeric argument as the number of lines.
171 Otherwise, interpret it as the number of bytes. */
172 static bool count_lines;
174 /* Whether we follow the name of each file or the file descriptor
175 that is initially associated with each name. */
176 static enum Follow_mode follow_mode = Follow_descriptor;
178 /* If true, read from the ends of all specified files until killed. */
179 static bool forever;
181 /* If true, count from start of file instead of end. */
182 static bool from_start;
184 /* If true, print filename headers. */
185 static bool print_headers;
187 /* When to print the filename banners. */
188 enum header_mode
190 multiple_files, always, never
193 /* When tailing a file by name, if there have been this many consecutive
194 iterations for which the file has not changed, then open/fstat
195 the file to determine if that file name is still associated with the
196 same device/inode-number pair as before. This option is meaningful only
197 when following by name. --max-unchanged-stats=N */
198 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
199 static uintmax_t max_n_unchanged_stats_between_opens =
200 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
202 /* The process ID of the process (presumably on the current host)
203 that is writing to all followed files. */
204 static pid_t pid;
206 /* True if we have ever read standard input. */
207 static bool have_read_stdin;
209 /* If nonzero, skip the is-regular-file test used to determine whether
210 to use the lseek optimization. Instead, use the more general (and
211 more expensive) code unconditionally. Intended solely for testing. */
212 static bool presume_input_pipe;
214 /* If nonzero then don't use inotify even if available. */
215 static bool disable_inotify;
217 /* For long options that have no equivalent short option, use a
218 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
219 enum
221 RETRY_OPTION = CHAR_MAX + 1,
222 MAX_UNCHANGED_STATS_OPTION,
223 PID_OPTION,
224 PRESUME_INPUT_PIPE_OPTION,
225 LONG_FOLLOW_OPTION,
226 DISABLE_INOTIFY_OPTION
229 static struct option const long_options[] =
231 {"bytes", required_argument, NULL, 'c'},
232 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
233 {"lines", required_argument, NULL, 'n'},
234 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
235 {"-disable-inotify", no_argument, NULL,
236 DISABLE_INOTIFY_OPTION}, /* do not document */
237 {"pid", required_argument, NULL, PID_OPTION},
238 {"-presume-input-pipe", no_argument, NULL,
239 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
240 {"quiet", no_argument, NULL, 'q'},
241 {"retry", no_argument, NULL, RETRY_OPTION},
242 {"silent", no_argument, NULL, 'q'},
243 {"sleep-interval", required_argument, NULL, 's'},
244 {"verbose", no_argument, NULL, 'v'},
245 {GETOPT_HELP_OPTION_DECL},
246 {GETOPT_VERSION_OPTION_DECL},
247 {NULL, 0, NULL, 0}
250 void
251 usage (int status)
253 if (status != EXIT_SUCCESS)
254 fprintf (stderr, _("Try `%s --help' for more information.\n"),
255 program_name);
256 else
258 printf (_("\
259 Usage: %s [OPTION]... [FILE]...\n\
261 program_name);
262 printf (_("\
263 Print the last %d lines of each FILE to standard output.\n\
264 With more than one FILE, precede each with a header giving the file name.\n\
265 With no FILE, or when FILE is -, read standard input.\n\
267 "), DEFAULT_N_LINES);
268 fputs (_("\
269 Mandatory arguments to long options are mandatory for short options too.\n\
270 "), stdout);
271 fputs (_("\
272 -c, --bytes=K output the last K bytes; alternatively, use -c +K\n\
273 to output bytes starting with the Kth of each file\n\
274 "), stdout);
275 fputs (_("\
276 -f, --follow[={name|descriptor}]\n\
277 output appended data as the file grows;\n\
278 -f, --follow, and --follow=descriptor are\n\
279 equivalent\n\
280 -F same as --follow=name --retry\n\
281 "), stdout);
282 printf (_("\
283 -n, --lines=K output the last K lines, instead of the last %d;\n\
284 or use -n +K to output lines starting with the Kth\n\
285 --max-unchanged-stats=N\n\
286 with --follow=name, reopen a FILE which has not\n\
287 changed size after N (default %d) iterations\n\
288 to see if it has been unlinked or renamed\n\
289 (this is the usual case of rotated log files)\n\
291 DEFAULT_N_LINES,
292 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
294 fputs (_("\
295 --pid=PID with -f, terminate after process ID, PID dies\n\
296 -q, --quiet, --silent never output headers giving file names\n\
297 --retry keep trying to open a file even when it is or\n\
298 becomes inaccessible; useful when following by\n\
299 name, i.e., with --follow=name\n\
300 "), stdout);
301 fputs (_("\
302 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
303 (default 1.0) between iterations\n\
304 -v, --verbose always output headers giving file names\n\
305 "), stdout);
306 fputs (HELP_OPTION_DESCRIPTION, stdout);
307 fputs (VERSION_OPTION_DESCRIPTION, stdout);
308 fputs (_("\
310 If the first character of K (the number of bytes or lines) is a `+',\n\
311 print beginning with the Kth item from the start of each file, otherwise,\n\
312 print the last K items in the file. K may have a multiplier suffix:\n\
313 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
314 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
316 "), stdout);
317 fputs (_("\
318 With --follow (-f), tail defaults to following the file descriptor, which\n\
319 means that even if a tail'ed file is renamed, tail will continue to track\n\
320 its end. This default behavior is not desirable when you really want to\n\
321 track the actual name of the file, not the file descriptor (e.g., log\n\
322 rotation). Use --follow=name in that case. That causes tail to track the\n\
323 named file in a way that accommodates renaming, removal and creation.\n\
324 "), stdout);
325 emit_ancillary_info ();
327 exit (status);
330 static bool
331 valid_file_spec (struct File_spec const *f)
333 /* Exactly one of the following subexpressions must be true. */
334 return ((f->fd == -1) ^ (f->errnum == 0));
337 static char const *
338 pretty_name (struct File_spec const *f)
340 return (STREQ (f->name, "-") ? _("standard input") : f->name);
343 static void
344 xwrite_stdout (char const *buffer, size_t n_bytes)
346 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
347 error (EXIT_FAILURE, errno, _("write error"));
350 /* Record a file F with descriptor FD, size SIZE, status ST, and
351 blocking status BLOCKING. */
353 static void
354 record_open_fd (struct File_spec *f, int fd,
355 off_t size, struct stat const *st,
356 int blocking)
358 f->fd = fd;
359 f->size = size;
360 f->mtime = get_stat_mtime (st);
361 f->dev = st->st_dev;
362 f->ino = st->st_ino;
363 f->mode = st->st_mode;
364 f->blocking = blocking;
365 f->n_unchanged_stats = 0;
366 f->ignore = false;
369 /* Close the file with descriptor FD and name FILENAME. */
371 static void
372 close_fd (int fd, const char *filename)
374 if (fd != -1 && fd != STDIN_FILENO && close (fd))
376 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
380 static void
381 write_header (const char *pretty_filename)
383 static bool first_file = true;
385 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
386 first_file = false;
389 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
390 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
391 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
392 Return the number of bytes read from the file. */
394 static uintmax_t
395 dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
397 uintmax_t n_written;
398 uintmax_t n_remaining = n_bytes;
400 n_written = 0;
401 while (1)
403 char buffer[BUFSIZ];
404 size_t n = MIN (n_remaining, BUFSIZ);
405 size_t bytes_read = safe_read (fd, buffer, n);
406 if (bytes_read == SAFE_READ_ERROR)
408 if (errno != EAGAIN)
409 error (EXIT_FAILURE, errno, _("error reading %s"),
410 quote (pretty_filename));
411 break;
413 if (bytes_read == 0)
414 break;
415 xwrite_stdout (buffer, bytes_read);
416 n_written += bytes_read;
417 if (n_bytes != COPY_TO_EOF)
419 n_remaining -= bytes_read;
420 if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
421 break;
425 return n_written;
428 /* Call lseek with the specified arguments, where file descriptor FD
429 corresponds to the file, FILENAME.
430 Give a diagnostic and exit nonzero if lseek fails.
431 Otherwise, return the resulting offset. */
433 static off_t
434 xlseek (int fd, off_t offset, int whence, char const *filename)
436 off_t new_offset = lseek (fd, offset, whence);
437 char buf[INT_BUFSIZE_BOUND (off_t)];
438 char *s;
440 if (0 <= new_offset)
441 return new_offset;
443 s = offtostr (offset, buf);
444 switch (whence)
446 case SEEK_SET:
447 error (0, errno, _("%s: cannot seek to offset %s"),
448 filename, s);
449 break;
450 case SEEK_CUR:
451 error (0, errno, _("%s: cannot seek to relative offset %s"),
452 filename, s);
453 break;
454 case SEEK_END:
455 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
456 filename, s);
457 break;
458 default:
459 abort ();
462 exit (EXIT_FAILURE);
465 /* Print the last N_LINES lines from the end of file FD.
466 Go backward through the file, reading `BUFSIZ' bytes at a time (except
467 probably the first), until we hit the start of the file or have
468 read NUMBER newlines.
469 START_POS is the starting position of the read pointer for the file
470 associated with FD (may be nonzero).
471 END_POS is the file offset of EOF (one larger than offset of last byte).
472 Return true if successful. */
474 static bool
475 file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
476 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
478 char buffer[BUFSIZ];
479 size_t bytes_read;
480 off_t pos = end_pos;
482 if (n_lines == 0)
483 return true;
485 /* Set `bytes_read' to the size of the last, probably partial, buffer;
486 0 < `bytes_read' <= `BUFSIZ'. */
487 bytes_read = (pos - start_pos) % BUFSIZ;
488 if (bytes_read == 0)
489 bytes_read = BUFSIZ;
490 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
491 reads will be on block boundaries, which might increase efficiency. */
492 pos -= bytes_read;
493 xlseek (fd, pos, SEEK_SET, pretty_filename);
494 bytes_read = safe_read (fd, buffer, bytes_read);
495 if (bytes_read == SAFE_READ_ERROR)
497 error (0, errno, _("error reading %s"), quote (pretty_filename));
498 return false;
500 *read_pos = pos + bytes_read;
502 /* Count the incomplete line on files that don't end with a newline. */
503 if (bytes_read && buffer[bytes_read - 1] != '\n')
504 --n_lines;
508 /* Scan backward, counting the newlines in this bufferfull. */
510 size_t n = bytes_read;
511 while (n)
513 char const *nl;
514 nl = memrchr (buffer, '\n', n);
515 if (nl == NULL)
516 break;
517 n = nl - buffer;
518 if (n_lines-- == 0)
520 /* If this newline isn't the last character in the buffer,
521 output the part that is after it. */
522 if (n != bytes_read - 1)
523 xwrite_stdout (nl + 1, bytes_read - (n + 1));
524 *read_pos += dump_remainder (pretty_filename, fd,
525 end_pos - (pos + bytes_read));
526 return true;
530 /* Not enough newlines in that bufferfull. */
531 if (pos == start_pos)
533 /* Not enough lines in the file; print everything from
534 start_pos to the end. */
535 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
536 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
537 end_pos);
538 return true;
540 pos -= BUFSIZ;
541 xlseek (fd, pos, SEEK_SET, pretty_filename);
543 bytes_read = safe_read (fd, buffer, BUFSIZ);
544 if (bytes_read == SAFE_READ_ERROR)
546 error (0, errno, _("error reading %s"), quote (pretty_filename));
547 return false;
550 *read_pos = pos + bytes_read;
552 while (bytes_read > 0);
554 return true;
557 /* Print the last N_LINES lines from the end of the standard input,
558 open for reading as pipe FD.
559 Buffer the text as a linked list of LBUFFERs, adding them as needed.
560 Return true if successful. */
562 static bool
563 pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
564 uintmax_t *read_pos)
566 struct linebuffer
568 char buffer[BUFSIZ];
569 size_t nbytes;
570 size_t nlines;
571 struct linebuffer *next;
573 typedef struct linebuffer LBUFFER;
574 LBUFFER *first, *last, *tmp;
575 size_t total_lines = 0; /* Total number of newlines in all buffers. */
576 bool ok = true;
577 size_t n_read; /* Size in bytes of most recent read */
579 first = last = xmalloc (sizeof (LBUFFER));
580 first->nbytes = first->nlines = 0;
581 first->next = NULL;
582 tmp = xmalloc (sizeof (LBUFFER));
584 /* Input is always read into a fresh buffer. */
585 while (1)
587 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
588 if (n_read == 0 || n_read == SAFE_READ_ERROR)
589 break;
590 tmp->nbytes = n_read;
591 *read_pos += n_read;
592 tmp->nlines = 0;
593 tmp->next = NULL;
595 /* Count the number of newlines just read. */
597 char const *buffer_end = tmp->buffer + n_read;
598 char const *p = tmp->buffer;
599 while ((p = memchr (p, '\n', buffer_end - p)))
601 ++p;
602 ++tmp->nlines;
605 total_lines += tmp->nlines;
607 /* If there is enough room in the last buffer read, just append the new
608 one to it. This is because when reading from a pipe, `n_read' can
609 often be very small. */
610 if (tmp->nbytes + last->nbytes < BUFSIZ)
612 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
613 last->nbytes += tmp->nbytes;
614 last->nlines += tmp->nlines;
616 else
618 /* If there's not enough room, link the new buffer onto the end of
619 the list, then either free up the oldest buffer for the next
620 read if that would leave enough lines, or else malloc a new one.
621 Some compaction mechanism is possible but probably not
622 worthwhile. */
623 last = last->next = tmp;
624 if (total_lines - first->nlines > n_lines)
626 tmp = first;
627 total_lines -= first->nlines;
628 first = first->next;
630 else
631 tmp = xmalloc (sizeof (LBUFFER));
635 free (tmp);
637 if (n_read == SAFE_READ_ERROR)
639 error (0, errno, _("error reading %s"), quote (pretty_filename));
640 ok = false;
641 goto free_lbuffers;
644 /* If the file is empty, then bail out. */
645 if (last->nbytes == 0)
646 goto free_lbuffers;
648 /* This prevents a core dump when the pipe contains no newlines. */
649 if (n_lines == 0)
650 goto free_lbuffers;
652 /* Count the incomplete line on files that don't end with a newline. */
653 if (last->buffer[last->nbytes - 1] != '\n')
655 ++last->nlines;
656 ++total_lines;
659 /* Run through the list, printing lines. First, skip over unneeded
660 buffers. */
661 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
662 total_lines -= tmp->nlines;
664 /* Find the correct beginning, then print the rest of the file. */
666 char const *beg = tmp->buffer;
667 char const *buffer_end = tmp->buffer + tmp->nbytes;
668 if (total_lines > n_lines)
670 /* Skip `total_lines' - `n_lines' newlines. We made sure that
671 `total_lines' - `n_lines' <= `tmp->nlines'. */
672 size_t j;
673 for (j = total_lines - n_lines; j; --j)
675 beg = memchr (beg, '\n', buffer_end - beg);
676 assert (beg);
677 ++beg;
681 xwrite_stdout (beg, buffer_end - beg);
684 for (tmp = tmp->next; tmp; tmp = tmp->next)
685 xwrite_stdout (tmp->buffer, tmp->nbytes);
687 free_lbuffers:
688 while (first)
690 tmp = first->next;
691 free (first);
692 first = tmp;
694 return ok;
697 /* Print the last N_BYTES characters from the end of pipe FD.
698 This is a stripped down version of pipe_lines.
699 Return true if successful. */
701 static bool
702 pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
703 uintmax_t *read_pos)
705 struct charbuffer
707 char buffer[BUFSIZ];
708 size_t nbytes;
709 struct charbuffer *next;
711 typedef struct charbuffer CBUFFER;
712 CBUFFER *first, *last, *tmp;
713 size_t i; /* Index into buffers. */
714 size_t total_bytes = 0; /* Total characters in all buffers. */
715 bool ok = true;
716 size_t n_read;
718 first = last = xmalloc (sizeof (CBUFFER));
719 first->nbytes = 0;
720 first->next = NULL;
721 tmp = xmalloc (sizeof (CBUFFER));
723 /* Input is always read into a fresh buffer. */
724 while (1)
726 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
727 if (n_read == 0 || n_read == SAFE_READ_ERROR)
728 break;
729 *read_pos += n_read;
730 tmp->nbytes = n_read;
731 tmp->next = NULL;
733 total_bytes += tmp->nbytes;
734 /* If there is enough room in the last buffer read, just append the new
735 one to it. This is because when reading from a pipe, `nbytes' can
736 often be very small. */
737 if (tmp->nbytes + last->nbytes < BUFSIZ)
739 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
740 last->nbytes += tmp->nbytes;
742 else
744 /* If there's not enough room, link the new buffer onto the end of
745 the list, then either free up the oldest buffer for the next
746 read if that would leave enough characters, or else malloc a new
747 one. Some compaction mechanism is possible but probably not
748 worthwhile. */
749 last = last->next = tmp;
750 if (total_bytes - first->nbytes > n_bytes)
752 tmp = first;
753 total_bytes -= first->nbytes;
754 first = first->next;
756 else
758 tmp = xmalloc (sizeof (CBUFFER));
763 free (tmp);
765 if (n_read == SAFE_READ_ERROR)
767 error (0, errno, _("error reading %s"), quote (pretty_filename));
768 ok = false;
769 goto free_cbuffers;
772 /* Run through the list, printing characters. First, skip over unneeded
773 buffers. */
774 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
775 total_bytes -= tmp->nbytes;
777 /* Find the correct beginning, then print the rest of the file.
778 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
779 if (total_bytes > n_bytes)
780 i = total_bytes - n_bytes;
781 else
782 i = 0;
783 xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
785 for (tmp = tmp->next; tmp; tmp = tmp->next)
786 xwrite_stdout (tmp->buffer, tmp->nbytes);
788 free_cbuffers:
789 while (first)
791 tmp = first->next;
792 free (first);
793 first = tmp;
795 return ok;
798 /* Skip N_BYTES characters from the start of pipe FD, and print
799 any extra characters that were read beyond that.
800 Return 1 on error, 0 if ok, -1 if EOF. */
802 static int
803 start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
804 uintmax_t *read_pos)
806 char buffer[BUFSIZ];
808 while (0 < n_bytes)
810 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
811 if (bytes_read == 0)
812 return -1;
813 if (bytes_read == SAFE_READ_ERROR)
815 error (0, errno, _("error reading %s"), quote (pretty_filename));
816 return 1;
818 read_pos += bytes_read;
819 if (bytes_read <= n_bytes)
820 n_bytes -= bytes_read;
821 else
823 size_t n_remaining = bytes_read - n_bytes;
824 if (n_remaining)
825 xwrite_stdout (&buffer[n_bytes], n_remaining);
826 break;
830 return 0;
833 /* Skip N_LINES lines at the start of file or pipe FD, and print
834 any extra characters that were read beyond that.
835 Return 1 on error, 0 if ok, -1 if EOF. */
837 static int
838 start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
839 uintmax_t *read_pos)
841 if (n_lines == 0)
842 return 0;
844 while (1)
846 char buffer[BUFSIZ];
847 char *p = buffer;
848 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
849 char *buffer_end = buffer + bytes_read;
850 if (bytes_read == 0) /* EOF */
851 return -1;
852 if (bytes_read == SAFE_READ_ERROR) /* error */
854 error (0, errno, _("error reading %s"), quote (pretty_filename));
855 return 1;
858 *read_pos += bytes_read;
860 while ((p = memchr (p, '\n', buffer_end - p)))
862 ++p;
863 if (--n_lines == 0)
865 if (p < buffer_end)
866 xwrite_stdout (p, buffer_end - p);
867 return 0;
873 #if HAVE_INOTIFY
874 /* Without inotify support, always return false. Otherwise, return false
875 when FD is open on a file known to reside on a local file system.
876 If fstatfs fails, give a diagnostic and return true.
877 If fstatfs cannot be called, return true. */
878 static bool
879 fremote (int fd, const char *name)
881 bool remote = true; /* be conservative (poll by default). */
883 # if HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE && defined __linux__
884 struct statfs buf;
885 int err = fstatfs (fd, &buf);
886 if (err != 0)
888 error (0, errno, _("cannot determine location of %s. "
889 "reverting to polling"), quote (name));
891 else
893 switch (buf.f_type)
895 case S_MAGIC_AFS:
896 case S_MAGIC_CIFS:
897 case S_MAGIC_CODA:
898 case S_MAGIC_FUSEBLK:
899 case S_MAGIC_FUSECTL:
900 case S_MAGIC_GFS:
901 case S_MAGIC_KAFS:
902 case S_MAGIC_LUSTRE:
903 case S_MAGIC_NCP:
904 case S_MAGIC_NFS:
905 case S_MAGIC_NFSD:
906 case S_MAGIC_OCFS2:
907 case S_MAGIC_SMB:
908 break;
909 default:
910 remote = false;
913 # endif
915 return remote;
917 #else
918 /* Without inotify support, whether a file is remote is irrelevant.
919 Always return "false" in that case. */
920 # define fremote(fd, name) false
921 #endif
923 /* FIXME: describe */
925 static void
926 recheck (struct File_spec *f, bool blocking)
928 /* open/fstat the file and announce if dev/ino have changed */
929 struct stat new_stats;
930 bool ok = true;
931 bool is_stdin = (STREQ (f->name, "-"));
932 bool was_tailable = f->tailable;
933 int prev_errnum = f->errnum;
934 bool new_file;
935 int fd = (is_stdin
936 ? STDIN_FILENO
937 : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
939 assert (valid_file_spec (f));
941 /* If the open fails because the file doesn't exist,
942 then mark the file as not tailable. */
943 f->tailable = !(reopen_inaccessible_files && fd == -1);
945 if (fd == -1 || fstat (fd, &new_stats) < 0)
947 ok = false;
948 f->errnum = errno;
949 if (!f->tailable)
951 if (was_tailable)
953 /* FIXME-maybe: detect the case in which the file first becomes
954 unreadable (perms), and later becomes readable again and can
955 be seen to be the same file (dev/ino). Otherwise, tail prints
956 the entire contents of the file when it becomes readable. */
957 error (0, f->errnum, _("%s has become inaccessible"),
958 quote (pretty_name (f)));
960 else
962 /* say nothing... it's still not tailable */
965 else if (prev_errnum != errno)
967 error (0, errno, "%s", pretty_name (f));
970 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
972 ok = false;
973 f->errnum = -1;
974 error (0, 0, _("%s has been replaced with an untailable file;\
975 giving up on this name"),
976 quote (pretty_name (f)));
977 f->ignore = true;
979 else if (!disable_inotify && fremote (fd, pretty_name (f)))
981 ok = false;
982 f->errnum = -1;
983 error (0, 0, _("%s has been replaced with a remote file. "
984 "giving up on this name"), quote (pretty_name (f)));
985 f->ignore = true;
986 f->remote = true;
988 else
990 f->errnum = 0;
993 new_file = false;
994 if (!ok)
996 close_fd (fd, pretty_name (f));
997 close_fd (f->fd, pretty_name (f));
998 f->fd = -1;
1000 else if (prev_errnum && prev_errnum != ENOENT)
1002 new_file = true;
1003 assert (f->fd == -1);
1004 error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
1006 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
1008 new_file = true;
1009 if (f->fd == -1)
1011 error (0, 0,
1012 _("%s has appeared; following end of new file"),
1013 quote (pretty_name (f)));
1015 else
1017 /* Close the old one. */
1018 close_fd (f->fd, pretty_name (f));
1020 /* File has been replaced (e.g., via log rotation) --
1021 tail the new one. */
1022 error (0, 0,
1023 _("%s has been replaced; following end of new file"),
1024 quote (pretty_name (f)));
1027 else
1029 if (f->fd == -1)
1031 /* This happens when one iteration finds the file missing,
1032 then the preceding <dev,inode> pair is reused as the
1033 file is recreated. */
1034 new_file = true;
1036 else
1038 close_fd (fd, pretty_name (f));
1042 if (new_file)
1044 /* Start at the beginning of the file. */
1045 record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
1046 xlseek (fd, 0, SEEK_SET, pretty_name (f));
1050 /* Return true if any of the N_FILES files in F are live, i.e., have
1051 open file descriptors. */
1053 static bool
1054 any_live_files (const struct File_spec *f, size_t n_files)
1056 size_t i;
1058 for (i = 0; i < n_files; i++)
1059 if (0 <= f[i].fd)
1060 return true;
1061 return false;
1064 /* Tail N_FILES files forever, or until killed.
1065 The pertinent information for each file is stored in an entry of F.
1066 Loop over each of them, doing an fstat to see if they have changed size,
1067 and an occasional open/fstat to see if any dev/ino pair has changed.
1068 If none of them have changed size in one iteration, sleep for a
1069 while and try again. Continue until the user interrupts us. */
1071 static void
1072 tail_forever (struct File_spec *f, size_t n_files, double sleep_interval)
1074 /* Use blocking I/O as an optimization, when it's easy. */
1075 bool blocking = (pid == 0 && follow_mode == Follow_descriptor
1076 && n_files == 1 && ! S_ISREG (f[0].mode));
1077 size_t last;
1078 bool writer_is_dead = false;
1080 last = n_files - 1;
1082 while (1)
1084 size_t i;
1085 bool any_input = false;
1087 for (i = 0; i < n_files; i++)
1089 int fd;
1090 char const *name;
1091 mode_t mode;
1092 struct stat stats;
1093 uintmax_t bytes_read;
1095 if (f[i].ignore)
1096 continue;
1098 if (f[i].fd < 0)
1100 recheck (&f[i], blocking);
1101 continue;
1104 fd = f[i].fd;
1105 name = pretty_name (&f[i]);
1106 mode = f[i].mode;
1108 if (f[i].blocking != blocking)
1110 int old_flags = fcntl (fd, F_GETFL);
1111 int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
1112 if (old_flags < 0
1113 || (new_flags != old_flags
1114 && fcntl (fd, F_SETFL, new_flags) == -1))
1116 /* Don't update f[i].blocking if fcntl fails. */
1117 if (S_ISREG (f[i].mode) && errno == EPERM)
1119 /* This happens when using tail -f on a file with
1120 the append-only attribute. */
1122 else
1123 error (EXIT_FAILURE, errno,
1124 _("%s: cannot change nonblocking mode"), name);
1126 else
1127 f[i].blocking = blocking;
1130 if (!f[i].blocking)
1132 if (fstat (fd, &stats) != 0)
1134 f[i].fd = -1;
1135 f[i].errnum = errno;
1136 error (0, errno, "%s", name);
1137 continue;
1140 if (f[i].mode == stats.st_mode
1141 && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
1142 && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
1144 if ((max_n_unchanged_stats_between_opens
1145 <= f[i].n_unchanged_stats++)
1146 && follow_mode == Follow_name)
1148 recheck (&f[i], f[i].blocking);
1149 f[i].n_unchanged_stats = 0;
1151 continue;
1154 /* This file has changed. Print out what we can, and
1155 then keep looping. */
1157 f[i].mtime = get_stat_mtime (&stats);
1158 f[i].mode = stats.st_mode;
1160 /* reset counter */
1161 f[i].n_unchanged_stats = 0;
1163 if (S_ISREG (mode) && stats.st_size < f[i].size)
1165 error (0, 0, _("%s: file truncated"), name);
1166 last = i;
1167 xlseek (fd, stats.st_size, SEEK_SET, name);
1168 f[i].size = stats.st_size;
1169 continue;
1172 if (i != last)
1174 if (print_headers)
1175 write_header (name);
1176 last = i;
1180 bytes_read = dump_remainder (name, fd,
1181 (f[i].blocking
1182 ? COPY_A_BUFFER : COPY_TO_EOF));
1183 any_input |= (bytes_read != 0);
1184 f[i].size += bytes_read;
1187 if (! any_live_files (f, n_files) && ! reopen_inaccessible_files)
1189 error (0, 0, _("no files remaining"));
1190 break;
1193 if ((!any_input || blocking) && fflush (stdout) != 0)
1194 error (EXIT_FAILURE, errno, _("write error"));
1196 /* If nothing was read, sleep and/or check for dead writers. */
1197 if (!any_input)
1199 if (writer_is_dead)
1200 break;
1202 /* Once the writer is dead, read the files once more to
1203 avoid a race condition. */
1204 writer_is_dead = (pid != 0
1205 && kill (pid, 0) != 0
1206 /* Handle the case in which you cannot send a
1207 signal to the writer, so kill fails and sets
1208 errno to EPERM. */
1209 && errno != EPERM);
1211 if (!writer_is_dead && xnanosleep (sleep_interval))
1212 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1218 #if HAVE_INOTIFY
1220 /* Return true if any of the N_FILES files in F is remote, i.e., has
1221 an open file descriptor and is on a network file system. */
1223 static bool
1224 any_remote_file (const struct File_spec *f, size_t n_files)
1226 size_t i;
1228 for (i = 0; i < n_files; i++)
1229 if (0 <= f[i].fd && f[i].remote)
1230 return true;
1231 return false;
1234 /* Return true if any of the N_FILES files in F represents
1235 stdin and is tailable. */
1237 static bool
1238 tailable_stdin (const struct File_spec *f, size_t n_files)
1240 size_t i;
1242 for (i = 0; i < n_files; i++)
1243 if (!f[i].ignore && STREQ (f[i].name, "-"))
1244 return true;
1245 return false;
1248 static size_t
1249 wd_hasher (const void *entry, size_t tabsize)
1251 const struct File_spec *spec = entry;
1252 return spec->wd % tabsize;
1255 static bool
1256 wd_comparator (const void *e1, const void *e2)
1258 const struct File_spec *spec1 = e1;
1259 const struct File_spec *spec2 = e2;
1260 return spec1->wd == spec2->wd;
1263 /* Helper function used by `tail_forever_inotify'. */
1264 static void
1265 check_fspec (struct File_spec *fspec, int wd, int *prev_wd)
1267 struct stat stats;
1268 char const *name = pretty_name (fspec);
1270 if (fstat (fspec->fd, &stats) != 0)
1272 close_fd (fspec->fd, name);
1273 fspec->fd = -1;
1274 fspec->errnum = errno;
1275 return;
1278 if (S_ISREG (fspec->mode) && stats.st_size < fspec->size)
1280 error (0, 0, _("%s: file truncated"), name);
1281 *prev_wd = wd;
1282 xlseek (fspec->fd, stats.st_size, SEEK_SET, name);
1283 fspec->size = stats.st_size;
1285 else if (S_ISREG (fspec->mode) && stats.st_size == fspec->size
1286 && timespec_cmp (fspec->mtime, get_stat_mtime (&stats)) == 0)
1287 return;
1289 if (wd != *prev_wd)
1291 if (print_headers)
1292 write_header (name);
1293 *prev_wd = wd;
1296 uintmax_t bytes_read = dump_remainder (name, fspec->fd, COPY_TO_EOF);
1297 fspec->size += bytes_read;
1299 if (fflush (stdout) != 0)
1300 error (EXIT_FAILURE, errno, _("write error"));
1303 /* Tail N_FILES files forever, or until killed.
1304 Check modifications using the inotify events system. */
1305 static void
1306 tail_forever_inotify (int wd, struct File_spec *f, size_t n_files,
1307 double sleep_interval)
1309 unsigned int max_realloc = 3;
1311 /* Map an inotify watch descriptor to the name of the file it's watching. */
1312 Hash_table *wd_to_name;
1314 bool found_watchable = false;
1315 bool writer_is_dead = false;
1316 int prev_wd;
1317 size_t evlen = 0;
1318 char *evbuf;
1319 size_t evbuf_off = 0;
1320 size_t len = 0;
1322 wd_to_name = hash_initialize (n_files, NULL, wd_hasher, wd_comparator, NULL);
1323 if (! wd_to_name)
1324 xalloc_die ();
1326 /* Add an inotify watch for each watched file. If -F is specified then watch
1327 its parent directory too, in this way when they re-appear we can add them
1328 again to the watch list. */
1329 size_t i;
1330 for (i = 0; i < n_files; i++)
1332 if (!f[i].ignore)
1334 size_t fnlen = strlen (f[i].name);
1335 if (evlen < fnlen)
1336 evlen = fnlen;
1338 f[i].wd = -1;
1340 if (follow_mode == Follow_name)
1342 size_t dirlen = dir_len (f[i].name);
1343 char prev = f[i].name[dirlen];
1344 f[i].basename_start = last_component (f[i].name) - f[i].name;
1346 f[i].name[dirlen] = '\0';
1348 /* It's fine to add the same directory more than once.
1349 In that case the same watch descriptor is returned. */
1350 f[i].parent_wd = inotify_add_watch (wd, dirlen ? f[i].name : ".",
1351 (IN_CREATE | IN_MOVED_TO
1352 | IN_ATTRIB));
1354 f[i].name[dirlen] = prev;
1356 if (f[i].parent_wd < 0)
1358 error (0, errno, _("cannot watch parent directory of %s"),
1359 quote (f[i].name));
1360 continue;
1364 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1366 if (f[i].wd < 0)
1368 if (errno != f[i].errnum)
1369 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1370 continue;
1373 if (hash_insert (wd_to_name, &(f[i])) == NULL)
1374 xalloc_die ();
1376 found_watchable = true;
1380 if (follow_mode == Follow_descriptor && !found_watchable)
1381 return;
1383 prev_wd = f[n_files - 1].wd;
1385 /* Check files again. New data can be available since last time we checked
1386 and before they are watched by inotify. */
1387 for (i = 0; i < n_files; i++)
1389 if (!f[i].ignore)
1390 check_fspec (&f[i], f[i].wd, &prev_wd);
1393 evlen += sizeof (struct inotify_event) + 1;
1394 evbuf = xmalloc (evlen);
1396 /* Wait for inotify events and handle them. Events on directories make sure
1397 that watched files can be re-added when -F is used.
1398 This loop sleeps on the `safe_read' call until a new event is notified. */
1399 while (1)
1401 struct File_spec *fspec;
1402 struct inotify_event *ev;
1404 /* When watching a PID, ensure that a read from WD will not block
1405 indefinitely. */
1406 if (pid)
1408 if (writer_is_dead)
1409 exit (EXIT_SUCCESS);
1411 writer_is_dead = (kill (pid, 0) != 0 && errno != EPERM);
1413 struct timeval delay; /* how long to wait for file changes. */
1414 if (writer_is_dead)
1415 delay.tv_sec = delay.tv_usec = 0;
1416 else
1418 delay.tv_sec = (time_t) sleep_interval;
1419 delay.tv_usec = 1000000 * (sleep_interval - delay.tv_sec);
1422 fd_set rfd;
1423 FD_ZERO (&rfd);
1424 FD_SET (wd, &rfd);
1426 int file_change = select (wd + 1, &rfd, NULL, NULL, &delay);
1428 if (file_change == 0)
1429 continue;
1430 else if (file_change == -1)
1431 error (EXIT_FAILURE, errno, _("error monitoring inotify event"));
1434 if (len <= evbuf_off)
1436 len = safe_read (wd, evbuf, evlen);
1437 evbuf_off = 0;
1439 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1440 is too small. */
1441 if ((len == 0 || (len == SAFE_READ_ERROR && errno == EINVAL))
1442 && max_realloc--)
1444 len = 0;
1445 evlen *= 2;
1446 evbuf = xrealloc (evbuf, evlen);
1447 continue;
1450 if (len == 0 || len == SAFE_READ_ERROR)
1451 error (EXIT_FAILURE, errno, _("error reading inotify event"));
1454 ev = (struct inotify_event *) (evbuf + evbuf_off);
1455 evbuf_off += sizeof (*ev) + ev->len;
1457 if (ev->len) /* event on ev->name in watched directory */
1459 size_t j;
1460 for (j = 0; j < n_files; j++)
1462 /* With N=hundreds of frequently-changing files, this O(N^2)
1463 process might be a problem. FIXME: use a hash table? */
1464 if (f[j].parent_wd == ev->wd
1465 && STREQ (ev->name, f[j].name + f[j].basename_start))
1466 break;
1469 /* It is not a watched file. */
1470 if (j == n_files)
1471 continue;
1473 /* It's fine to add the same file more than once. */
1474 int new_wd = inotify_add_watch (wd, f[j].name, inotify_wd_mask);
1475 if (new_wd < 0)
1477 error (0, errno, _("cannot watch %s"), quote (f[j].name));
1478 continue;
1481 fspec = &(f[j]);
1483 /* Remove `fspec' and re-add it using `new_fd' as its key. */
1484 hash_delete (wd_to_name, fspec);
1485 fspec->wd = new_wd;
1487 /* If the file was moved then inotify will use the source file wd for
1488 the destination file. Make sure the key is not present in the
1489 table. */
1490 struct File_spec *prev = hash_delete (wd_to_name, fspec);
1491 if (prev && prev != fspec)
1493 if (follow_mode == Follow_name)
1494 recheck (prev, false);
1495 prev->wd = -1;
1496 close_fd (prev->fd, pretty_name (prev));
1499 if (hash_insert (wd_to_name, fspec) == NULL)
1500 xalloc_die ();
1502 if (follow_mode == Follow_name)
1503 recheck (fspec, false);
1505 else
1507 struct File_spec key;
1508 key.wd = ev->wd;
1509 fspec = hash_lookup (wd_to_name, &key);
1512 if (! fspec)
1513 continue;
1515 if (ev->mask & (IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF))
1517 /* For IN_DELETE_SELF, we always want to remove the watch.
1518 However, for IN_MOVE_SELF (the file we're watching has
1519 been clobbered via a rename), when tailing by NAME, we
1520 must continue to watch the file. It's only when following
1521 by file descriptor that we must remove the watch. */
1522 if ((ev->mask & IN_DELETE_SELF)
1523 || ((ev->mask & IN_MOVE_SELF) && follow_mode == Follow_descriptor))
1525 inotify_rm_watch (wd, fspec->wd);
1526 hash_delete (wd_to_name, fspec);
1528 if (follow_mode == Follow_name)
1529 recheck (fspec, false);
1531 continue;
1533 check_fspec (fspec, ev->wd, &prev_wd);
1536 #endif
1538 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1539 Return true if successful. */
1541 static bool
1542 tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1543 uintmax_t *read_pos)
1545 struct stat stats;
1547 if (fstat (fd, &stats))
1549 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1550 return false;
1553 if (from_start)
1555 if ( ! presume_input_pipe
1556 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1558 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1559 *read_pos += n_bytes;
1561 else
1563 int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
1564 if (t)
1565 return t < 0;
1567 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1569 else
1571 if ( ! presume_input_pipe
1572 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1574 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1575 off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename);
1576 off_t diff = end_pos - current_pos;
1577 /* Be careful here. The current position may actually be
1578 beyond the end of the file. */
1579 off_t bytes_remaining = diff < 0 ? 0 : diff;
1580 off_t nb = n_bytes;
1582 if (bytes_remaining <= nb)
1584 /* From the current position to end of file, there are no
1585 more bytes than have been requested. So reposition the
1586 file pointer to the incoming current position and print
1587 everything after that. */
1588 *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1590 else
1592 /* There are more bytes remaining than were requested.
1593 Back up. */
1594 *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename);
1596 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1598 else
1599 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1601 return true;
1604 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1605 Return true if successful. */
1607 static bool
1608 tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1609 uintmax_t *read_pos)
1611 struct stat stats;
1613 if (fstat (fd, &stats))
1615 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1616 return false;
1619 if (from_start)
1621 int t = start_lines (pretty_filename, fd, n_lines, read_pos);
1622 if (t)
1623 return t < 0;
1624 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1626 else
1628 off_t start_pos = -1;
1629 off_t end_pos;
1631 /* Use file_lines only if FD refers to a regular file for
1632 which lseek (... SEEK_END) works. */
1633 if ( ! presume_input_pipe
1634 && S_ISREG (stats.st_mode)
1635 && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
1636 && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
1638 *read_pos = end_pos;
1639 if (end_pos != 0
1640 && ! file_lines (pretty_filename, fd, n_lines,
1641 start_pos, end_pos, read_pos))
1642 return false;
1644 else
1646 /* Under very unlikely circumstances, it is possible to reach
1647 this point after positioning the file pointer to end of file
1648 via the `lseek (...SEEK_END)' above. In that case, reposition
1649 the file pointer back to start_pos before calling pipe_lines. */
1650 if (start_pos != -1)
1651 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1653 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1656 return true;
1659 /* Display the last N_UNITS units of file FILENAME, open for reading
1660 via FD. Set *READ_POS to the position of the input stream pointer.
1661 *READ_POS is usually the number of bytes read and corresponds to an
1662 offset from the beginning of a file. However, it may be larger than
1663 OFF_T_MAX (as for an input pipe), and may also be larger than the
1664 number of bytes read (when an input pointer is initially not at
1665 beginning of file), and may be far greater than the number of bytes
1666 actually read for an input file that is seekable.
1667 Return true if successful. */
1669 static bool
1670 tail (const char *filename, int fd, uintmax_t n_units,
1671 uintmax_t *read_pos)
1673 *read_pos = 0;
1674 if (count_lines)
1675 return tail_lines (filename, fd, n_units, read_pos);
1676 else
1677 return tail_bytes (filename, fd, n_units, read_pos);
1680 /* Display the last N_UNITS units of the file described by F.
1681 Return true if successful. */
1683 static bool
1684 tail_file (struct File_spec *f, uintmax_t n_units)
1686 int fd;
1687 bool ok;
1689 bool is_stdin = (STREQ (f->name, "-"));
1691 if (is_stdin)
1693 have_read_stdin = true;
1694 fd = STDIN_FILENO;
1695 if (O_BINARY && ! isatty (STDIN_FILENO))
1696 xfreopen (NULL, "rb", stdin);
1698 else
1699 fd = open (f->name, O_RDONLY | O_BINARY);
1701 f->tailable = !(reopen_inaccessible_files && fd == -1);
1703 if (fd == -1)
1705 if (forever)
1707 f->fd = -1;
1708 f->errnum = errno;
1709 f->ignore = false;
1710 f->ino = 0;
1711 f->dev = 0;
1713 error (0, errno, _("cannot open %s for reading"),
1714 quote (pretty_name (f)));
1715 ok = false;
1717 else
1719 uintmax_t read_pos;
1721 if (print_headers)
1722 write_header (pretty_name (f));
1723 ok = tail (pretty_name (f), fd, n_units, &read_pos);
1724 if (forever)
1726 struct stat stats;
1728 #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
1729 /* Before the tail function provided `read_pos', there was
1730 a race condition described in the URL below. This sleep
1731 call made the window big enough to exercise the problem. */
1732 xnanosleep (1);
1733 #endif
1734 f->errnum = ok - 1;
1735 if (fstat (fd, &stats) < 0)
1737 ok = false;
1738 f->errnum = errno;
1739 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1741 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1743 error (0, 0, _("%s: cannot follow end of this type of file;\
1744 giving up on this name"),
1745 pretty_name (f));
1746 ok = false;
1747 f->errnum = -1;
1748 f->ignore = true;
1751 if (!ok)
1753 close_fd (fd, pretty_name (f));
1754 f->fd = -1;
1756 else
1758 /* Note: we must use read_pos here, not stats.st_size,
1759 to avoid a race condition described by Ken Raeburn:
1760 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1761 record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
1762 f->remote = fremote (fd, pretty_name (f));
1765 else
1767 if (!is_stdin && close (fd))
1769 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1770 ok = false;
1775 return ok;
1778 /* If obsolete usage is allowed, and the command line arguments are of
1779 the obsolete form and the option string is well-formed, set
1780 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1781 return true. If the command line arguments are obviously incorrect
1782 (e.g., because obsolete usage is not allowed and the arguments are
1783 incorrect for non-obsolete usage), report an error and exit.
1784 Otherwise, return false and don't modify any parameter or global
1785 variable. */
1787 static bool
1788 parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
1790 const char *p;
1791 const char *n_string;
1792 const char *n_string_end;
1793 bool obsolete_usage;
1794 int default_count = DEFAULT_N_LINES;
1795 bool t_from_start;
1796 bool t_count_lines = true;
1797 bool t_forever = false;
1799 /* With the obsolete form, there is one option string and at most
1800 one file argument. Watch out for "-" and "--", though. */
1801 if (! (argc == 2
1802 || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
1803 || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
1804 return false;
1806 obsolete_usage = (posix2_version () < 200112);
1807 p = argv[1];
1809 switch (*p++)
1811 default:
1812 return false;
1814 case '+':
1815 /* Leading "+" is a file name in the non-obsolete form. */
1816 if (!obsolete_usage)
1817 return false;
1819 t_from_start = true;
1820 break;
1822 case '-':
1823 /* In the non-obsolete form, "-" is standard input and "-c"
1824 requires an option-argument. The obsolete multidigit options
1825 are supported as a GNU extension even when conforming to
1826 POSIX 1003.1-2001, so don't complain about them. */
1827 if (!obsolete_usage && !p[p[0] == 'c'])
1828 return false;
1830 t_from_start = false;
1831 break;
1834 n_string = p;
1835 while (ISDIGIT (*p))
1836 p++;
1837 n_string_end = p;
1839 switch (*p)
1841 case 'b': default_count *= 512; /* Fall through. */
1842 case 'c': t_count_lines = false; /* Fall through. */
1843 case 'l': p++; break;
1846 if (*p == 'f')
1848 t_forever = true;
1849 ++p;
1852 if (*p)
1853 return false;
1855 if (n_string == n_string_end)
1856 *n_units = default_count;
1857 else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
1858 & ~LONGINT_INVALID_SUFFIX_CHAR)
1859 != LONGINT_OK)
1860 error (EXIT_FAILURE, 0, _("number in %s is too large"), quote (argv[1]));
1862 /* Set globals. */
1863 from_start = t_from_start;
1864 count_lines = t_count_lines;
1865 forever = t_forever;
1867 return true;
1870 static void
1871 parse_options (int argc, char **argv,
1872 uintmax_t *n_units, enum header_mode *header_mode,
1873 double *sleep_interval)
1875 int c;
1877 while ((c = getopt_long (argc, argv, "c:n:fFqs:v0123456789",
1878 long_options, NULL))
1879 != -1)
1881 switch (c)
1883 case 'F':
1884 forever = true;
1885 follow_mode = Follow_name;
1886 reopen_inaccessible_files = true;
1887 break;
1889 case 'c':
1890 case 'n':
1891 count_lines = (c == 'n');
1892 if (*optarg == '+')
1893 from_start = true;
1894 else if (*optarg == '-')
1895 ++optarg;
1898 strtol_error s_err;
1899 s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkKmMGTPEZY0");
1900 if (s_err != LONGINT_OK)
1902 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1903 (c == 'n'
1904 ? _("invalid number of lines")
1905 : _("invalid number of bytes")));
1908 break;
1910 case 'f':
1911 case LONG_FOLLOW_OPTION:
1912 forever = true;
1913 if (optarg == NULL)
1914 follow_mode = DEFAULT_FOLLOW_MODE;
1915 else
1916 follow_mode = XARGMATCH ("--follow", optarg,
1917 follow_mode_string, follow_mode_map);
1918 break;
1920 case RETRY_OPTION:
1921 reopen_inaccessible_files = true;
1922 break;
1924 case MAX_UNCHANGED_STATS_OPTION:
1925 /* --max-unchanged-stats=N */
1926 if (xstrtoumax (optarg, NULL, 10,
1927 &max_n_unchanged_stats_between_opens,
1929 != LONGINT_OK)
1931 error (EXIT_FAILURE, 0,
1932 _("%s: invalid maximum number of unchanged stats between opens"),
1933 optarg);
1935 break;
1937 case DISABLE_INOTIFY_OPTION:
1938 disable_inotify = true;
1939 break;
1941 case PID_OPTION:
1943 strtol_error s_err;
1944 unsigned long int tmp_ulong;
1945 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1946 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1948 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1950 pid = tmp_ulong;
1952 break;
1954 case PRESUME_INPUT_PIPE_OPTION:
1955 presume_input_pipe = true;
1956 break;
1958 case 'q':
1959 *header_mode = never;
1960 break;
1962 case 's':
1964 double s;
1965 if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
1966 error (EXIT_FAILURE, 0,
1967 _("%s: invalid number of seconds"), optarg);
1968 *sleep_interval = s;
1970 break;
1972 case 'v':
1973 *header_mode = always;
1974 break;
1976 case_GETOPT_HELP_CHAR;
1978 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1980 case '0': case '1': case '2': case '3': case '4':
1981 case '5': case '6': case '7': case '8': case '9':
1982 error (EXIT_FAILURE, 0,
1983 _("option used in invalid context -- %c"), c);
1985 default:
1986 usage (EXIT_FAILURE);
1990 if (reopen_inaccessible_files && follow_mode != Follow_name)
1991 error (0, 0, _("warning: --retry is useful mainly when following by name"));
1993 if (pid && !forever)
1994 error (0, 0,
1995 _("warning: PID ignored; --pid=PID is useful only when following"));
1996 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
1998 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1999 pid = 0;
2003 /* Mark as '.ignore'd each member of F that corresponds to a
2004 pipe or fifo, and return the number of non-ignored members. */
2005 static size_t
2006 ignore_fifo_and_pipe (struct File_spec *f, size_t n_files)
2008 /* When there is no FILE operand and stdin is a pipe or FIFO
2009 POSIX requires that tail ignore the -f option.
2010 Since we allow multiple FILE operands, we extend that to say: with -f,
2011 ignore any "-" operand that corresponds to a pipe or FIFO. */
2012 size_t n_viable = 0;
2014 size_t i;
2015 for (i = 0; i < n_files; i++)
2017 bool is_a_fifo_or_pipe =
2018 (STREQ (f[i].name, "-")
2019 && !f[i].ignore
2020 && 0 <= f[i].fd
2021 && (S_ISFIFO (f[i].mode)
2022 || (HAVE_FIFO_PIPES != 1 && isapipe (f[i].fd))));
2023 if (is_a_fifo_or_pipe)
2024 f[i].ignore = true;
2025 else
2026 ++n_viable;
2029 return n_viable;
2033 main (int argc, char **argv)
2035 enum header_mode header_mode = multiple_files;
2036 bool ok = true;
2037 /* If from_start, the number of items to skip before printing; otherwise,
2038 the number of items at the end of the file to print. Although the type
2039 is signed, the value is never negative. */
2040 uintmax_t n_units = DEFAULT_N_LINES;
2041 size_t n_files;
2042 char **file;
2043 struct File_spec *F;
2044 size_t i;
2045 bool obsolete_option;
2047 /* The number of seconds to sleep between iterations.
2048 During one iteration, every file name or descriptor is checked to
2049 see if it has changed. */
2050 double sleep_interval = 1.0;
2052 initialize_main (&argc, &argv);
2053 set_program_name (argv[0]);
2054 setlocale (LC_ALL, "");
2055 bindtextdomain (PACKAGE, LOCALEDIR);
2056 textdomain (PACKAGE);
2058 atexit (close_stdout);
2060 have_read_stdin = false;
2062 count_lines = true;
2063 forever = from_start = print_headers = false;
2064 obsolete_option = parse_obsolete_option (argc, argv, &n_units);
2065 argc -= obsolete_option;
2066 argv += obsolete_option;
2067 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
2069 /* To start printing with item N_UNITS from the start of the file, skip
2070 N_UNITS - 1 items. `tail -n +0' is actually meaningless, but for Unix
2071 compatibility it's treated the same as `tail -n +1'. */
2072 if (from_start)
2074 if (n_units)
2075 --n_units;
2078 if (optind < argc)
2080 n_files = argc - optind;
2081 file = argv + optind;
2083 else
2085 static char *dummy_stdin = (char *) "-";
2086 n_files = 1;
2087 file = &dummy_stdin;
2091 bool found_hyphen = false;
2093 for (i = 0; i < n_files; i++)
2094 if (STREQ (file[i], "-"))
2095 found_hyphen = true;
2097 /* When following by name, there must be a name. */
2098 if (found_hyphen && follow_mode == Follow_name)
2099 error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quote ("-"));
2101 /* When following forever, warn if any file is `-'.
2102 This is only a warning, since tail's output (before a failing seek,
2103 and that from any non-stdin files) might still be useful. */
2104 if (forever && found_hyphen && isatty (STDIN_FILENO))
2105 error (0, 0, _("warning: following standard input"
2106 " indefinitely is ineffective"));
2109 F = xnmalloc (n_files, sizeof *F);
2110 for (i = 0; i < n_files; i++)
2111 F[i].name = file[i];
2113 if (header_mode == always
2114 || (header_mode == multiple_files && n_files > 1))
2115 print_headers = true;
2117 if (O_BINARY && ! isatty (STDOUT_FILENO))
2118 xfreopen (NULL, "wb", stdout);
2120 for (i = 0; i < n_files; i++)
2121 ok &= tail_file (&F[i], n_units);
2123 if (forever && ignore_fifo_and_pipe (F, n_files))
2125 #if HAVE_INOTIFY
2126 /* tailable_stdin() checks if the user specifies stdin via "-",
2127 or implicitly by providing no arguments. If so, we won't use inotify.
2128 Technically, on systems with a working /dev/stdin, we *could*,
2129 but would it be worth it? Verifying that it's a real device
2130 and hooked up to stdin is not trivial, while reverting to
2131 non-inotify-based tail_forever is easy and portable.
2133 any_remote_file() checks if the user has specified any
2134 files that reside on remote file systems. inotify is not used
2135 in this case because it would miss any updates to the file
2136 that were not initiated from the local system.
2138 FIXME: inotify doesn't give any notification when a new
2139 (remote) file or directory is mounted on top a watched file.
2140 When follow_mode == Follow_name we would ideally like to detect that.
2141 Note if there is a change to the original file then we'll
2142 recheck it and follow the new file, or ignore it if the
2143 file has changed to being remote. */
2144 if (tailable_stdin (F, n_files) || any_remote_file (F, n_files))
2145 disable_inotify = true;
2147 if (!disable_inotify)
2149 int wd = inotify_init ();
2150 if (wd < 0)
2151 error (0, errno, _("inotify cannot be used, reverting to polling"));
2152 else
2154 /* Flush any output from tail_file, now, since
2155 tail_forever_inotify flushes only after writing,
2156 not before reading. */
2157 if (fflush (stdout) != 0)
2158 error (EXIT_FAILURE, errno, _("write error"));
2160 tail_forever_inotify (wd, F, n_files, sleep_interval);
2162 /* The only way the above returns is upon failure. */
2163 exit (EXIT_FAILURE);
2166 #endif
2167 tail_forever (F, n_files, sleep_interval);
2170 if (have_read_stdin && close (STDIN_FILENO) < 0)
2171 error (EXIT_FAILURE, errno, "-");
2172 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);