fiemap copy: don't let write failure go unreported; adjust style, etc.
[coreutils.git] / src / tail.c
blobbcd2d99701883ff2f803f2a3b1fc3354fef614b5
1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989-1991, 1995-2006, 2008-2011 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\
290 With inotify, this option is rarely useful.\n\
292 DEFAULT_N_LINES,
293 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
295 fputs (_("\
296 --pid=PID with -f, terminate after process ID, PID dies\n\
297 -q, --quiet, --silent never output headers giving file names\n\
298 --retry keep trying to open a file even when it is or\n\
299 becomes inaccessible; useful when following by\n\
300 name, i.e., with --follow=name\n\
301 "), stdout);
302 fputs (_("\
303 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
304 (default 1.0) between iterations.\n\
305 With inotify, this option is rarely useful.\n\
306 -v, --verbose always output headers giving file names\n\
307 "), stdout);
308 fputs (HELP_OPTION_DESCRIPTION, stdout);
309 fputs (VERSION_OPTION_DESCRIPTION, stdout);
310 fputs (_("\
312 If the first character of K (the number of bytes or lines) is a `+',\n\
313 print beginning with the Kth item from the start of each file, otherwise,\n\
314 print the last K items in the file. K may have a multiplier suffix:\n\
315 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
316 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
318 "), stdout);
319 fputs (_("\
320 With --follow (-f), tail defaults to following the file descriptor, which\n\
321 means that even if a tail'ed file is renamed, tail will continue to track\n\
322 its end. This default behavior is not desirable when you really want to\n\
323 track the actual name of the file, not the file descriptor (e.g., log\n\
324 rotation). Use --follow=name in that case. That causes tail to track the\n\
325 named file in a way that accommodates renaming, removal and creation.\n\
326 "), stdout);
327 emit_ancillary_info ();
329 exit (status);
332 static bool
333 valid_file_spec (struct File_spec const *f)
335 /* Exactly one of the following subexpressions must be true. */
336 return ((f->fd == -1) ^ (f->errnum == 0));
339 static char const *
340 pretty_name (struct File_spec const *f)
342 return (STREQ (f->name, "-") ? _("standard input") : f->name);
345 static void
346 xwrite_stdout (char const *buffer, size_t n_bytes)
348 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
349 error (EXIT_FAILURE, errno, _("write error"));
352 /* Record a file F with descriptor FD, size SIZE, status ST, and
353 blocking status BLOCKING. */
355 static void
356 record_open_fd (struct File_spec *f, int fd,
357 off_t size, struct stat const *st,
358 int blocking)
360 f->fd = fd;
361 f->size = size;
362 f->mtime = get_stat_mtime (st);
363 f->dev = st->st_dev;
364 f->ino = st->st_ino;
365 f->mode = st->st_mode;
366 f->blocking = blocking;
367 f->n_unchanged_stats = 0;
368 f->ignore = false;
371 /* Close the file with descriptor FD and name FILENAME. */
373 static void
374 close_fd (int fd, const char *filename)
376 if (fd != -1 && fd != STDIN_FILENO && close (fd))
378 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
382 static void
383 write_header (const char *pretty_filename)
385 static bool first_file = true;
387 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
388 first_file = false;
391 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
392 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
393 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
394 Return the number of bytes read from the file. */
396 static uintmax_t
397 dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
399 uintmax_t n_written;
400 uintmax_t n_remaining = n_bytes;
402 n_written = 0;
403 while (1)
405 char buffer[BUFSIZ];
406 size_t n = MIN (n_remaining, BUFSIZ);
407 size_t bytes_read = safe_read (fd, buffer, n);
408 if (bytes_read == SAFE_READ_ERROR)
410 if (errno != EAGAIN)
411 error (EXIT_FAILURE, errno, _("error reading %s"),
412 quote (pretty_filename));
413 break;
415 if (bytes_read == 0)
416 break;
417 xwrite_stdout (buffer, bytes_read);
418 n_written += bytes_read;
419 if (n_bytes != COPY_TO_EOF)
421 n_remaining -= bytes_read;
422 if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
423 break;
427 return n_written;
430 /* Call lseek with the specified arguments, where file descriptor FD
431 corresponds to the file, FILENAME.
432 Give a diagnostic and exit nonzero if lseek fails.
433 Otherwise, return the resulting offset. */
435 static off_t
436 xlseek (int fd, off_t offset, int whence, char const *filename)
438 off_t new_offset = lseek (fd, offset, whence);
439 char buf[INT_BUFSIZE_BOUND (offset)];
440 char *s;
442 if (0 <= new_offset)
443 return new_offset;
445 s = offtostr (offset, buf);
446 switch (whence)
448 case SEEK_SET:
449 error (0, errno, _("%s: cannot seek to offset %s"),
450 filename, s);
451 break;
452 case SEEK_CUR:
453 error (0, errno, _("%s: cannot seek to relative offset %s"),
454 filename, s);
455 break;
456 case SEEK_END:
457 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
458 filename, s);
459 break;
460 default:
461 abort ();
464 exit (EXIT_FAILURE);
467 /* Print the last N_LINES lines from the end of file FD.
468 Go backward through the file, reading `BUFSIZ' bytes at a time (except
469 probably the first), until we hit the start of the file or have
470 read NUMBER newlines.
471 START_POS is the starting position of the read pointer for the file
472 associated with FD (may be nonzero).
473 END_POS is the file offset of EOF (one larger than offset of last byte).
474 Return true if successful. */
476 static bool
477 file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
478 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
480 char buffer[BUFSIZ];
481 size_t bytes_read;
482 off_t pos = end_pos;
484 if (n_lines == 0)
485 return true;
487 /* Set `bytes_read' to the size of the last, probably partial, buffer;
488 0 < `bytes_read' <= `BUFSIZ'. */
489 bytes_read = (pos - start_pos) % BUFSIZ;
490 if (bytes_read == 0)
491 bytes_read = BUFSIZ;
492 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
493 reads will be on block boundaries, which might increase efficiency. */
494 pos -= bytes_read;
495 xlseek (fd, pos, SEEK_SET, pretty_filename);
496 bytes_read = safe_read (fd, buffer, bytes_read);
497 if (bytes_read == SAFE_READ_ERROR)
499 error (0, errno, _("error reading %s"), quote (pretty_filename));
500 return false;
502 *read_pos = pos + bytes_read;
504 /* Count the incomplete line on files that don't end with a newline. */
505 if (bytes_read && buffer[bytes_read - 1] != '\n')
506 --n_lines;
510 /* Scan backward, counting the newlines in this bufferfull. */
512 size_t n = bytes_read;
513 while (n)
515 char const *nl;
516 nl = memrchr (buffer, '\n', n);
517 if (nl == NULL)
518 break;
519 n = nl - buffer;
520 if (n_lines-- == 0)
522 /* If this newline isn't the last character in the buffer,
523 output the part that is after it. */
524 if (n != bytes_read - 1)
525 xwrite_stdout (nl + 1, bytes_read - (n + 1));
526 *read_pos += dump_remainder (pretty_filename, fd,
527 end_pos - (pos + bytes_read));
528 return true;
532 /* Not enough newlines in that bufferfull. */
533 if (pos == start_pos)
535 /* Not enough lines in the file; print everything from
536 start_pos to the end. */
537 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
538 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
539 end_pos);
540 return true;
542 pos -= BUFSIZ;
543 xlseek (fd, pos, SEEK_SET, pretty_filename);
545 bytes_read = safe_read (fd, buffer, BUFSIZ);
546 if (bytes_read == SAFE_READ_ERROR)
548 error (0, errno, _("error reading %s"), quote (pretty_filename));
549 return false;
552 *read_pos = pos + bytes_read;
554 while (bytes_read > 0);
556 return true;
559 /* Print the last N_LINES lines from the end of the standard input,
560 open for reading as pipe FD.
561 Buffer the text as a linked list of LBUFFERs, adding them as needed.
562 Return true if successful. */
564 static bool
565 pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
566 uintmax_t *read_pos)
568 struct linebuffer
570 char buffer[BUFSIZ];
571 size_t nbytes;
572 size_t nlines;
573 struct linebuffer *next;
575 typedef struct linebuffer LBUFFER;
576 LBUFFER *first, *last, *tmp;
577 size_t total_lines = 0; /* Total number of newlines in all buffers. */
578 bool ok = true;
579 size_t n_read; /* Size in bytes of most recent read */
581 first = last = xmalloc (sizeof (LBUFFER));
582 first->nbytes = first->nlines = 0;
583 first->next = NULL;
584 tmp = xmalloc (sizeof (LBUFFER));
586 /* Input is always read into a fresh buffer. */
587 while (1)
589 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
590 if (n_read == 0 || n_read == SAFE_READ_ERROR)
591 break;
592 tmp->nbytes = n_read;
593 *read_pos += n_read;
594 tmp->nlines = 0;
595 tmp->next = NULL;
597 /* Count the number of newlines just read. */
599 char const *buffer_end = tmp->buffer + n_read;
600 char const *p = tmp->buffer;
601 while ((p = memchr (p, '\n', buffer_end - p)))
603 ++p;
604 ++tmp->nlines;
607 total_lines += tmp->nlines;
609 /* If there is enough room in the last buffer read, just append the new
610 one to it. This is because when reading from a pipe, `n_read' can
611 often be very small. */
612 if (tmp->nbytes + last->nbytes < BUFSIZ)
614 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
615 last->nbytes += tmp->nbytes;
616 last->nlines += tmp->nlines;
618 else
620 /* If there's not enough room, link the new buffer onto the end of
621 the list, then either free up the oldest buffer for the next
622 read if that would leave enough lines, or else malloc a new one.
623 Some compaction mechanism is possible but probably not
624 worthwhile. */
625 last = last->next = tmp;
626 if (total_lines - first->nlines > n_lines)
628 tmp = first;
629 total_lines -= first->nlines;
630 first = first->next;
632 else
633 tmp = xmalloc (sizeof (LBUFFER));
637 free (tmp);
639 if (n_read == SAFE_READ_ERROR)
641 error (0, errno, _("error reading %s"), quote (pretty_filename));
642 ok = false;
643 goto free_lbuffers;
646 /* If the file is empty, then bail out. */
647 if (last->nbytes == 0)
648 goto free_lbuffers;
650 /* This prevents a core dump when the pipe contains no newlines. */
651 if (n_lines == 0)
652 goto free_lbuffers;
654 /* Count the incomplete line on files that don't end with a newline. */
655 if (last->buffer[last->nbytes - 1] != '\n')
657 ++last->nlines;
658 ++total_lines;
661 /* Run through the list, printing lines. First, skip over unneeded
662 buffers. */
663 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
664 total_lines -= tmp->nlines;
666 /* Find the correct beginning, then print the rest of the file. */
668 char const *beg = tmp->buffer;
669 char const *buffer_end = tmp->buffer + tmp->nbytes;
670 if (total_lines > n_lines)
672 /* Skip `total_lines' - `n_lines' newlines. We made sure that
673 `total_lines' - `n_lines' <= `tmp->nlines'. */
674 size_t j;
675 for (j = total_lines - n_lines; j; --j)
677 beg = memchr (beg, '\n', buffer_end - beg);
678 assert (beg);
679 ++beg;
683 xwrite_stdout (beg, buffer_end - beg);
686 for (tmp = tmp->next; tmp; tmp = tmp->next)
687 xwrite_stdout (tmp->buffer, tmp->nbytes);
689 free_lbuffers:
690 while (first)
692 tmp = first->next;
693 free (first);
694 first = tmp;
696 return ok;
699 /* Print the last N_BYTES characters from the end of pipe FD.
700 This is a stripped down version of pipe_lines.
701 Return true if successful. */
703 static bool
704 pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
705 uintmax_t *read_pos)
707 struct charbuffer
709 char buffer[BUFSIZ];
710 size_t nbytes;
711 struct charbuffer *next;
713 typedef struct charbuffer CBUFFER;
714 CBUFFER *first, *last, *tmp;
715 size_t i; /* Index into buffers. */
716 size_t total_bytes = 0; /* Total characters in all buffers. */
717 bool ok = true;
718 size_t n_read;
720 first = last = xmalloc (sizeof (CBUFFER));
721 first->nbytes = 0;
722 first->next = NULL;
723 tmp = xmalloc (sizeof (CBUFFER));
725 /* Input is always read into a fresh buffer. */
726 while (1)
728 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
729 if (n_read == 0 || n_read == SAFE_READ_ERROR)
730 break;
731 *read_pos += n_read;
732 tmp->nbytes = n_read;
733 tmp->next = NULL;
735 total_bytes += tmp->nbytes;
736 /* If there is enough room in the last buffer read, just append the new
737 one to it. This is because when reading from a pipe, `nbytes' can
738 often be very small. */
739 if (tmp->nbytes + last->nbytes < BUFSIZ)
741 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
742 last->nbytes += tmp->nbytes;
744 else
746 /* If there's not enough room, link the new buffer onto the end of
747 the list, then either free up the oldest buffer for the next
748 read if that would leave enough characters, or else malloc a new
749 one. Some compaction mechanism is possible but probably not
750 worthwhile. */
751 last = last->next = tmp;
752 if (total_bytes - first->nbytes > n_bytes)
754 tmp = first;
755 total_bytes -= first->nbytes;
756 first = first->next;
758 else
760 tmp = xmalloc (sizeof (CBUFFER));
765 free (tmp);
767 if (n_read == SAFE_READ_ERROR)
769 error (0, errno, _("error reading %s"), quote (pretty_filename));
770 ok = false;
771 goto free_cbuffers;
774 /* Run through the list, printing characters. First, skip over unneeded
775 buffers. */
776 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
777 total_bytes -= tmp->nbytes;
779 /* Find the correct beginning, then print the rest of the file.
780 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
781 if (total_bytes > n_bytes)
782 i = total_bytes - n_bytes;
783 else
784 i = 0;
785 xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
787 for (tmp = tmp->next; tmp; tmp = tmp->next)
788 xwrite_stdout (tmp->buffer, tmp->nbytes);
790 free_cbuffers:
791 while (first)
793 tmp = first->next;
794 free (first);
795 first = tmp;
797 return ok;
800 /* Skip N_BYTES characters from the start of pipe FD, and print
801 any extra characters that were read beyond that.
802 Return 1 on error, 0 if ok, -1 if EOF. */
804 static int
805 start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
806 uintmax_t *read_pos)
808 char buffer[BUFSIZ];
810 while (0 < n_bytes)
812 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
813 if (bytes_read == 0)
814 return -1;
815 if (bytes_read == SAFE_READ_ERROR)
817 error (0, errno, _("error reading %s"), quote (pretty_filename));
818 return 1;
820 read_pos += bytes_read;
821 if (bytes_read <= n_bytes)
822 n_bytes -= bytes_read;
823 else
825 size_t n_remaining = bytes_read - n_bytes;
826 if (n_remaining)
827 xwrite_stdout (&buffer[n_bytes], n_remaining);
828 break;
832 return 0;
835 /* Skip N_LINES lines at the start of file or pipe FD, and print
836 any extra characters that were read beyond that.
837 Return 1 on error, 0 if ok, -1 if EOF. */
839 static int
840 start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
841 uintmax_t *read_pos)
843 if (n_lines == 0)
844 return 0;
846 while (1)
848 char buffer[BUFSIZ];
849 char *p = buffer;
850 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
851 char *buffer_end = buffer + bytes_read;
852 if (bytes_read == 0) /* EOF */
853 return -1;
854 if (bytes_read == SAFE_READ_ERROR) /* error */
856 error (0, errno, _("error reading %s"), quote (pretty_filename));
857 return 1;
860 *read_pos += bytes_read;
862 while ((p = memchr (p, '\n', buffer_end - p)))
864 ++p;
865 if (--n_lines == 0)
867 if (p < buffer_end)
868 xwrite_stdout (p, buffer_end - p);
869 return 0;
875 #if HAVE_INOTIFY
876 /* Without inotify support, always return false. Otherwise, return false
877 when FD is open on a file known to reside on a local file system.
878 If fstatfs fails, give a diagnostic and return true.
879 If fstatfs cannot be called, return true. */
880 static bool
881 fremote (int fd, const char *name)
883 bool remote = true; /* be conservative (poll by default). */
885 # if HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE && defined __linux__
886 struct statfs buf;
887 int err = fstatfs (fd, &buf);
888 if (err != 0)
890 /* On at least linux-2.6.38, fstatfs fails with ENOSYS when FD
891 is open on a pipe. Treat that like a remote file. */
892 if (errno != ENOSYS)
893 error (0, errno, _("cannot determine location of %s. "
894 "reverting to polling"), quote (name));
896 else
898 switch (buf.f_type)
900 case S_MAGIC_AFS:
901 case S_MAGIC_CIFS:
902 case S_MAGIC_CODA:
903 case S_MAGIC_FUSEBLK:
904 case S_MAGIC_FUSECTL:
905 case S_MAGIC_GFS:
906 case S_MAGIC_KAFS:
907 case S_MAGIC_LUSTRE:
908 case S_MAGIC_NCP:
909 case S_MAGIC_NFS:
910 case S_MAGIC_NFSD:
911 case S_MAGIC_OCFS2:
912 case S_MAGIC_SMB:
913 break;
914 default:
915 remote = false;
918 # endif
920 return remote;
922 #else
923 /* Without inotify support, whether a file is remote is irrelevant.
924 Always return "false" in that case. */
925 # define fremote(fd, name) false
926 #endif
928 /* FIXME: describe */
930 static void
931 recheck (struct File_spec *f, bool blocking)
933 /* open/fstat the file and announce if dev/ino have changed */
934 struct stat new_stats;
935 bool ok = true;
936 bool is_stdin = (STREQ (f->name, "-"));
937 bool was_tailable = f->tailable;
938 int prev_errnum = f->errnum;
939 bool new_file;
940 int fd = (is_stdin
941 ? STDIN_FILENO
942 : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
944 assert (valid_file_spec (f));
946 /* If the open fails because the file doesn't exist,
947 then mark the file as not tailable. */
948 f->tailable = !(reopen_inaccessible_files && fd == -1);
950 if (fd == -1 || fstat (fd, &new_stats) < 0)
952 ok = false;
953 f->errnum = errno;
954 if (!f->tailable)
956 if (was_tailable)
958 /* FIXME-maybe: detect the case in which the file first becomes
959 unreadable (perms), and later becomes readable again and can
960 be seen to be the same file (dev/ino). Otherwise, tail prints
961 the entire contents of the file when it becomes readable. */
962 error (0, f->errnum, _("%s has become inaccessible"),
963 quote (pretty_name (f)));
965 else
967 /* say nothing... it's still not tailable */
970 else if (prev_errnum != errno)
972 error (0, errno, "%s", pretty_name (f));
975 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
977 ok = false;
978 f->errnum = -1;
979 error (0, 0, _("%s has been replaced with an untailable file;\
980 giving up on this name"),
981 quote (pretty_name (f)));
982 f->ignore = true;
984 else if (!disable_inotify && fremote (fd, pretty_name (f)))
986 ok = false;
987 f->errnum = -1;
988 error (0, 0, _("%s has been replaced with a remote file. "
989 "giving up on this name"), quote (pretty_name (f)));
990 f->ignore = true;
991 f->remote = true;
993 else
995 f->errnum = 0;
998 new_file = false;
999 if (!ok)
1001 close_fd (fd, pretty_name (f));
1002 close_fd (f->fd, pretty_name (f));
1003 f->fd = -1;
1005 else if (prev_errnum && prev_errnum != ENOENT)
1007 new_file = true;
1008 assert (f->fd == -1);
1009 error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
1011 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
1013 new_file = true;
1014 if (f->fd == -1)
1016 error (0, 0,
1017 _("%s has appeared; following end of new file"),
1018 quote (pretty_name (f)));
1020 else
1022 /* Close the old one. */
1023 close_fd (f->fd, pretty_name (f));
1025 /* File has been replaced (e.g., via log rotation) --
1026 tail the new one. */
1027 error (0, 0,
1028 _("%s has been replaced; following end of new file"),
1029 quote (pretty_name (f)));
1032 else
1034 if (f->fd == -1)
1036 /* This happens when one iteration finds the file missing,
1037 then the preceding <dev,inode> pair is reused as the
1038 file is recreated. */
1039 new_file = true;
1041 else
1043 close_fd (fd, pretty_name (f));
1047 if (new_file)
1049 /* Start at the beginning of the file. */
1050 record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
1051 xlseek (fd, 0, SEEK_SET, pretty_name (f));
1055 /* Return true if any of the N_FILES files in F are live, i.e., have
1056 open file descriptors. */
1058 static bool
1059 any_live_files (const struct File_spec *f, size_t n_files)
1061 size_t i;
1063 for (i = 0; i < n_files; i++)
1064 if (0 <= f[i].fd)
1065 return true;
1066 return false;
1069 /* Tail N_FILES files forever, or until killed.
1070 The pertinent information for each file is stored in an entry of F.
1071 Loop over each of them, doing an fstat to see if they have changed size,
1072 and an occasional open/fstat to see if any dev/ino pair has changed.
1073 If none of them have changed size in one iteration, sleep for a
1074 while and try again. Continue until the user interrupts us. */
1076 static void
1077 tail_forever (struct File_spec *f, size_t n_files, double sleep_interval)
1079 /* Use blocking I/O as an optimization, when it's easy. */
1080 bool blocking = (pid == 0 && follow_mode == Follow_descriptor
1081 && n_files == 1 && ! S_ISREG (f[0].mode));
1082 size_t last;
1083 bool writer_is_dead = false;
1085 last = n_files - 1;
1087 while (1)
1089 size_t i;
1090 bool any_input = false;
1092 for (i = 0; i < n_files; i++)
1094 int fd;
1095 char const *name;
1096 mode_t mode;
1097 struct stat stats;
1098 uintmax_t bytes_read;
1100 if (f[i].ignore)
1101 continue;
1103 if (f[i].fd < 0)
1105 recheck (&f[i], blocking);
1106 continue;
1109 fd = f[i].fd;
1110 name = pretty_name (&f[i]);
1111 mode = f[i].mode;
1113 if (f[i].blocking != blocking)
1115 int old_flags = fcntl (fd, F_GETFL);
1116 int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
1117 if (old_flags < 0
1118 || (new_flags != old_flags
1119 && fcntl (fd, F_SETFL, new_flags) == -1))
1121 /* Don't update f[i].blocking if fcntl fails. */
1122 if (S_ISREG (f[i].mode) && errno == EPERM)
1124 /* This happens when using tail -f on a file with
1125 the append-only attribute. */
1127 else
1128 error (EXIT_FAILURE, errno,
1129 _("%s: cannot change nonblocking mode"), name);
1131 else
1132 f[i].blocking = blocking;
1135 if (!f[i].blocking)
1137 if (fstat (fd, &stats) != 0)
1139 f[i].fd = -1;
1140 f[i].errnum = errno;
1141 error (0, errno, "%s", name);
1142 continue;
1145 if (f[i].mode == stats.st_mode
1146 && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
1147 && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
1149 if ((max_n_unchanged_stats_between_opens
1150 <= f[i].n_unchanged_stats++)
1151 && follow_mode == Follow_name)
1153 recheck (&f[i], f[i].blocking);
1154 f[i].n_unchanged_stats = 0;
1156 continue;
1159 /* This file has changed. Print out what we can, and
1160 then keep looping. */
1162 f[i].mtime = get_stat_mtime (&stats);
1163 f[i].mode = stats.st_mode;
1165 /* reset counter */
1166 f[i].n_unchanged_stats = 0;
1168 if (S_ISREG (mode) && stats.st_size < f[i].size)
1170 error (0, 0, _("%s: file truncated"), name);
1171 last = i;
1172 xlseek (fd, stats.st_size, SEEK_SET, name);
1173 f[i].size = stats.st_size;
1174 continue;
1177 if (i != last)
1179 if (print_headers)
1180 write_header (name);
1181 last = i;
1185 bytes_read = dump_remainder (name, fd,
1186 (f[i].blocking
1187 ? COPY_A_BUFFER : COPY_TO_EOF));
1188 any_input |= (bytes_read != 0);
1189 f[i].size += bytes_read;
1192 if (! any_live_files (f, n_files) && ! reopen_inaccessible_files)
1194 error (0, 0, _("no files remaining"));
1195 break;
1198 if ((!any_input || blocking) && fflush (stdout) != 0)
1199 error (EXIT_FAILURE, errno, _("write error"));
1201 /* If nothing was read, sleep and/or check for dead writers. */
1202 if (!any_input)
1204 if (writer_is_dead)
1205 break;
1207 /* Once the writer is dead, read the files once more to
1208 avoid a race condition. */
1209 writer_is_dead = (pid != 0
1210 && kill (pid, 0) != 0
1211 /* Handle the case in which you cannot send a
1212 signal to the writer, so kill fails and sets
1213 errno to EPERM. */
1214 && errno != EPERM);
1216 if (!writer_is_dead && xnanosleep (sleep_interval))
1217 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1223 #if HAVE_INOTIFY
1225 /* Return true if any of the N_FILES files in F is remote, i.e., has
1226 an open file descriptor and is on a network file system. */
1228 static bool
1229 any_remote_file (const struct File_spec *f, size_t n_files)
1231 size_t i;
1233 for (i = 0; i < n_files; i++)
1234 if (0 <= f[i].fd && f[i].remote)
1235 return true;
1236 return false;
1239 /* Return true if any of the N_FILES files in F represents
1240 stdin and is tailable. */
1242 static bool
1243 tailable_stdin (const struct File_spec *f, size_t n_files)
1245 size_t i;
1247 for (i = 0; i < n_files; i++)
1248 if (!f[i].ignore && STREQ (f[i].name, "-"))
1249 return true;
1250 return false;
1253 static size_t
1254 wd_hasher (const void *entry, size_t tabsize)
1256 const struct File_spec *spec = entry;
1257 return spec->wd % tabsize;
1260 static bool
1261 wd_comparator (const void *e1, const void *e2)
1263 const struct File_spec *spec1 = e1;
1264 const struct File_spec *spec2 = e2;
1265 return spec1->wd == spec2->wd;
1268 /* Helper function used by `tail_forever_inotify'. */
1269 static void
1270 check_fspec (struct File_spec *fspec, int wd, int *prev_wd)
1272 struct stat stats;
1273 char const *name = pretty_name (fspec);
1275 if (fstat (fspec->fd, &stats) != 0)
1277 close_fd (fspec->fd, name);
1278 fspec->fd = -1;
1279 fspec->errnum = errno;
1280 return;
1283 if (S_ISREG (fspec->mode) && stats.st_size < fspec->size)
1285 error (0, 0, _("%s: file truncated"), name);
1286 *prev_wd = wd;
1287 xlseek (fspec->fd, stats.st_size, SEEK_SET, name);
1288 fspec->size = stats.st_size;
1290 else if (S_ISREG (fspec->mode) && stats.st_size == fspec->size
1291 && timespec_cmp (fspec->mtime, get_stat_mtime (&stats)) == 0)
1292 return;
1294 if (wd != *prev_wd)
1296 if (print_headers)
1297 write_header (name);
1298 *prev_wd = wd;
1301 uintmax_t bytes_read = dump_remainder (name, fspec->fd, COPY_TO_EOF);
1302 fspec->size += bytes_read;
1304 if (fflush (stdout) != 0)
1305 error (EXIT_FAILURE, errno, _("write error"));
1308 /* Attempt to tail N_FILES files forever, or until killed.
1309 Check modifications using the inotify events system.
1310 Return false on error, or true to revert to polling. */
1311 static bool
1312 tail_forever_inotify (int wd, struct File_spec *f, size_t n_files,
1313 double sleep_interval)
1315 unsigned int max_realloc = 3;
1317 /* Map an inotify watch descriptor to the name of the file it's watching. */
1318 Hash_table *wd_to_name;
1320 bool found_watchable_file = false;
1321 bool found_unwatchable_dir = false;
1322 bool no_inotify_resources = false;
1323 bool writer_is_dead = false;
1324 int prev_wd;
1325 size_t evlen = 0;
1326 char *evbuf;
1327 size_t evbuf_off = 0;
1328 size_t len = 0;
1330 wd_to_name = hash_initialize (n_files, NULL, wd_hasher, wd_comparator, NULL);
1331 if (! wd_to_name)
1332 xalloc_die ();
1334 /* Add an inotify watch for each watched file. If -F is specified then watch
1335 its parent directory too, in this way when they re-appear we can add them
1336 again to the watch list. */
1337 size_t i;
1338 for (i = 0; i < n_files; i++)
1340 if (!f[i].ignore)
1342 size_t fnlen = strlen (f[i].name);
1343 if (evlen < fnlen)
1344 evlen = fnlen;
1346 f[i].wd = -1;
1348 if (follow_mode == Follow_name)
1350 size_t dirlen = dir_len (f[i].name);
1351 char prev = f[i].name[dirlen];
1352 f[i].basename_start = last_component (f[i].name) - f[i].name;
1354 f[i].name[dirlen] = '\0';
1356 /* It's fine to add the same directory more than once.
1357 In that case the same watch descriptor is returned. */
1358 f[i].parent_wd = inotify_add_watch (wd, dirlen ? f[i].name : ".",
1359 (IN_CREATE | IN_MOVED_TO
1360 | IN_ATTRIB));
1362 f[i].name[dirlen] = prev;
1364 if (f[i].parent_wd < 0)
1366 if (errno != ENOSPC) /* suppress confusing error. */
1367 error (0, errno, _("cannot watch parent directory of %s"),
1368 quote (f[i].name));
1369 else
1370 error (0, 0, _("inotify resources exhausted"));
1371 found_unwatchable_dir = true;
1372 /* We revert to polling below. Note invalid uses
1373 of the inotify API will still be diagnosed. */
1374 break;
1378 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1380 if (f[i].wd < 0)
1382 if (errno == ENOSPC)
1384 no_inotify_resources = true;
1385 error (0, 0, _("inotify resources exhausted"));
1387 else if (errno != f[i].errnum)
1388 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1389 continue;
1392 if (hash_insert (wd_to_name, &(f[i])) == NULL)
1393 xalloc_die ();
1395 found_watchable_file = true;
1399 /* Linux kernel 2.6.24 at least has a bug where eventually, ENOSPC is always
1400 returned by inotify_add_watch. In any case we should revert to polling
1401 when there are no inotify resources. Also a specified directory may not
1402 be currently present or accessible, so revert to polling. */
1403 if (no_inotify_resources || found_unwatchable_dir)
1405 /* FIXME: release hash and inotify resources allocated above. */
1406 errno = 0;
1407 return true;
1409 if (follow_mode == Follow_descriptor && !found_watchable_file)
1410 return false;
1412 prev_wd = f[n_files - 1].wd;
1414 /* Check files again. New data can be available since last time we checked
1415 and before they are watched by inotify. */
1416 for (i = 0; i < n_files; i++)
1418 if (!f[i].ignore)
1419 check_fspec (&f[i], f[i].wd, &prev_wd);
1422 evlen += sizeof (struct inotify_event) + 1;
1423 evbuf = xmalloc (evlen);
1425 /* Wait for inotify events and handle them. Events on directories make sure
1426 that watched files can be re-added when -F is used.
1427 This loop sleeps on the `safe_read' call until a new event is notified. */
1428 while (1)
1430 struct File_spec *fspec;
1431 struct inotify_event *ev;
1433 /* When watching a PID, ensure that a read from WD will not block
1434 indefinitely. */
1435 if (pid)
1437 if (writer_is_dead)
1438 exit (EXIT_SUCCESS);
1440 writer_is_dead = (kill (pid, 0) != 0 && errno != EPERM);
1442 struct timeval delay; /* how long to wait for file changes. */
1443 if (writer_is_dead)
1444 delay.tv_sec = delay.tv_usec = 0;
1445 else
1447 delay.tv_sec = (time_t) sleep_interval;
1448 delay.tv_usec = 1000000 * (sleep_interval - delay.tv_sec);
1451 fd_set rfd;
1452 FD_ZERO (&rfd);
1453 FD_SET (wd, &rfd);
1455 int file_change = select (wd + 1, &rfd, NULL, NULL, &delay);
1457 if (file_change == 0)
1458 continue;
1459 else if (file_change == -1)
1460 error (EXIT_FAILURE, errno, _("error monitoring inotify event"));
1463 if (len <= evbuf_off)
1465 len = safe_read (wd, evbuf, evlen);
1466 evbuf_off = 0;
1468 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1469 is too small. */
1470 if ((len == 0 || (len == SAFE_READ_ERROR && errno == EINVAL))
1471 && max_realloc--)
1473 len = 0;
1474 evlen *= 2;
1475 evbuf = xrealloc (evbuf, evlen);
1476 continue;
1479 if (len == 0 || len == SAFE_READ_ERROR)
1480 error (EXIT_FAILURE, errno, _("error reading inotify event"));
1483 ev = (struct inotify_event *) (evbuf + evbuf_off);
1484 evbuf_off += sizeof (*ev) + ev->len;
1486 if (ev->len) /* event on ev->name in watched directory */
1488 size_t j;
1489 for (j = 0; j < n_files; j++)
1491 /* With N=hundreds of frequently-changing files, this O(N^2)
1492 process might be a problem. FIXME: use a hash table? */
1493 if (f[j].parent_wd == ev->wd
1494 && STREQ (ev->name, f[j].name + f[j].basename_start))
1495 break;
1498 /* It is not a watched file. */
1499 if (j == n_files)
1500 continue;
1502 /* It's fine to add the same file more than once. */
1503 int new_wd = inotify_add_watch (wd, f[j].name, inotify_wd_mask);
1504 if (new_wd < 0)
1506 error (0, errno, _("cannot watch %s"), quote (f[j].name));
1507 continue;
1510 fspec = &(f[j]);
1512 /* Remove `fspec' and re-add it using `new_fd' as its key. */
1513 hash_delete (wd_to_name, fspec);
1514 fspec->wd = new_wd;
1516 /* If the file was moved then inotify will use the source file wd for
1517 the destination file. Make sure the key is not present in the
1518 table. */
1519 struct File_spec *prev = hash_delete (wd_to_name, fspec);
1520 if (prev && prev != fspec)
1522 if (follow_mode == Follow_name)
1523 recheck (prev, false);
1524 prev->wd = -1;
1525 close_fd (prev->fd, pretty_name (prev));
1528 if (hash_insert (wd_to_name, fspec) == NULL)
1529 xalloc_die ();
1531 if (follow_mode == Follow_name)
1532 recheck (fspec, false);
1534 else
1536 struct File_spec key;
1537 key.wd = ev->wd;
1538 fspec = hash_lookup (wd_to_name, &key);
1541 if (! fspec)
1542 continue;
1544 if (ev->mask & (IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF))
1546 /* For IN_DELETE_SELF, we always want to remove the watch.
1547 However, for IN_MOVE_SELF (the file we're watching has
1548 been clobbered via a rename), when tailing by NAME, we
1549 must continue to watch the file. It's only when following
1550 by file descriptor that we must remove the watch. */
1551 if ((ev->mask & IN_DELETE_SELF)
1552 || ((ev->mask & IN_MOVE_SELF)
1553 && follow_mode == Follow_descriptor))
1555 inotify_rm_watch (wd, fspec->wd);
1556 hash_delete (wd_to_name, fspec);
1558 if (follow_mode == Follow_name)
1559 recheck (fspec, false);
1561 continue;
1563 check_fspec (fspec, ev->wd, &prev_wd);
1566 #endif
1568 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1569 Return true if successful. */
1571 static bool
1572 tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1573 uintmax_t *read_pos)
1575 struct stat stats;
1577 if (fstat (fd, &stats))
1579 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1580 return false;
1583 if (from_start)
1585 if ( ! presume_input_pipe
1586 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1588 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1589 *read_pos += n_bytes;
1591 else
1593 int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
1594 if (t)
1595 return t < 0;
1597 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1599 else
1601 if ( ! presume_input_pipe
1602 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1604 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1605 off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename);
1606 off_t diff = end_pos - current_pos;
1607 /* Be careful here. The current position may actually be
1608 beyond the end of the file. */
1609 off_t bytes_remaining = diff < 0 ? 0 : diff;
1610 off_t nb = n_bytes;
1612 if (bytes_remaining <= nb)
1614 /* From the current position to end of file, there are no
1615 more bytes than have been requested. So reposition the
1616 file pointer to the incoming current position and print
1617 everything after that. */
1618 *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1620 else
1622 /* There are more bytes remaining than were requested.
1623 Back up. */
1624 *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename);
1626 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1628 else
1629 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1631 return true;
1634 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1635 Return true if successful. */
1637 static bool
1638 tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1639 uintmax_t *read_pos)
1641 struct stat stats;
1643 if (fstat (fd, &stats))
1645 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1646 return false;
1649 if (from_start)
1651 int t = start_lines (pretty_filename, fd, n_lines, read_pos);
1652 if (t)
1653 return t < 0;
1654 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1656 else
1658 off_t start_pos = -1;
1659 off_t end_pos;
1661 /* Use file_lines only if FD refers to a regular file for
1662 which lseek (... SEEK_END) works. */
1663 if ( ! presume_input_pipe
1664 && S_ISREG (stats.st_mode)
1665 && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
1666 && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
1668 *read_pos = end_pos;
1669 if (end_pos != 0
1670 && ! file_lines (pretty_filename, fd, n_lines,
1671 start_pos, end_pos, read_pos))
1672 return false;
1674 else
1676 /* Under very unlikely circumstances, it is possible to reach
1677 this point after positioning the file pointer to end of file
1678 via the `lseek (...SEEK_END)' above. In that case, reposition
1679 the file pointer back to start_pos before calling pipe_lines. */
1680 if (start_pos != -1)
1681 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1683 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1686 return true;
1689 /* Display the last N_UNITS units of file FILENAME, open for reading
1690 via FD. Set *READ_POS to the position of the input stream pointer.
1691 *READ_POS is usually the number of bytes read and corresponds to an
1692 offset from the beginning of a file. However, it may be larger than
1693 OFF_T_MAX (as for an input pipe), and may also be larger than the
1694 number of bytes read (when an input pointer is initially not at
1695 beginning of file), and may be far greater than the number of bytes
1696 actually read for an input file that is seekable.
1697 Return true if successful. */
1699 static bool
1700 tail (const char *filename, int fd, uintmax_t n_units,
1701 uintmax_t *read_pos)
1703 *read_pos = 0;
1704 if (count_lines)
1705 return tail_lines (filename, fd, n_units, read_pos);
1706 else
1707 return tail_bytes (filename, fd, n_units, read_pos);
1710 /* Display the last N_UNITS units of the file described by F.
1711 Return true if successful. */
1713 static bool
1714 tail_file (struct File_spec *f, uintmax_t n_units)
1716 int fd;
1717 bool ok;
1719 bool is_stdin = (STREQ (f->name, "-"));
1721 if (is_stdin)
1723 have_read_stdin = true;
1724 fd = STDIN_FILENO;
1725 if (O_BINARY && ! isatty (STDIN_FILENO))
1726 xfreopen (NULL, "rb", stdin);
1728 else
1729 fd = open (f->name, O_RDONLY | O_BINARY);
1731 f->tailable = !(reopen_inaccessible_files && fd == -1);
1733 if (fd == -1)
1735 if (forever)
1737 f->fd = -1;
1738 f->errnum = errno;
1739 f->ignore = false;
1740 f->ino = 0;
1741 f->dev = 0;
1743 error (0, errno, _("cannot open %s for reading"),
1744 quote (pretty_name (f)));
1745 ok = false;
1747 else
1749 uintmax_t read_pos;
1751 if (print_headers)
1752 write_header (pretty_name (f));
1753 ok = tail (pretty_name (f), fd, n_units, &read_pos);
1754 if (forever)
1756 struct stat stats;
1758 #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
1759 /* Before the tail function provided `read_pos', there was
1760 a race condition described in the URL below. This sleep
1761 call made the window big enough to exercise the problem. */
1762 xnanosleep (1);
1763 #endif
1764 f->errnum = ok - 1;
1765 if (fstat (fd, &stats) < 0)
1767 ok = false;
1768 f->errnum = errno;
1769 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1771 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1773 error (0, 0, _("%s: cannot follow end of this type of file;\
1774 giving up on this name"),
1775 pretty_name (f));
1776 ok = false;
1777 f->errnum = -1;
1778 f->ignore = true;
1781 if (!ok)
1783 close_fd (fd, pretty_name (f));
1784 f->fd = -1;
1786 else
1788 /* Note: we must use read_pos here, not stats.st_size,
1789 to avoid a race condition described by Ken Raeburn:
1790 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1791 record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
1792 f->remote = fremote (fd, pretty_name (f));
1795 else
1797 if (!is_stdin && close (fd))
1799 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1800 ok = false;
1805 return ok;
1808 /* If obsolete usage is allowed, and the command line arguments are of
1809 the obsolete form and the option string is well-formed, set
1810 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1811 return true. If the command line arguments are obviously incorrect
1812 (e.g., because obsolete usage is not allowed and the arguments are
1813 incorrect for non-obsolete usage), report an error and exit.
1814 Otherwise, return false and don't modify any parameter or global
1815 variable. */
1817 static bool
1818 parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
1820 const char *p;
1821 const char *n_string;
1822 const char *n_string_end;
1823 bool obsolete_usage;
1824 int default_count = DEFAULT_N_LINES;
1825 bool t_from_start;
1826 bool t_count_lines = true;
1827 bool t_forever = false;
1829 /* With the obsolete form, there is one option string and at most
1830 one file argument. Watch out for "-" and "--", though. */
1831 if (! (argc == 2
1832 || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
1833 || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
1834 return false;
1836 obsolete_usage = (posix2_version () < 200112);
1837 p = argv[1];
1839 switch (*p++)
1841 default:
1842 return false;
1844 case '+':
1845 /* Leading "+" is a file name in the non-obsolete form. */
1846 if (!obsolete_usage)
1847 return false;
1849 t_from_start = true;
1850 break;
1852 case '-':
1853 /* In the non-obsolete form, "-" is standard input and "-c"
1854 requires an option-argument. The obsolete multidigit options
1855 are supported as a GNU extension even when conforming to
1856 POSIX 1003.1-2001, so don't complain about them. */
1857 if (!obsolete_usage && !p[p[0] == 'c'])
1858 return false;
1860 t_from_start = false;
1861 break;
1864 n_string = p;
1865 while (ISDIGIT (*p))
1866 p++;
1867 n_string_end = p;
1869 switch (*p)
1871 case 'b': default_count *= 512; /* Fall through. */
1872 case 'c': t_count_lines = false; /* Fall through. */
1873 case 'l': p++; break;
1876 if (*p == 'f')
1878 t_forever = true;
1879 ++p;
1882 if (*p)
1883 return false;
1885 if (n_string == n_string_end)
1886 *n_units = default_count;
1887 else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
1888 & ~LONGINT_INVALID_SUFFIX_CHAR)
1889 != LONGINT_OK)
1890 error (EXIT_FAILURE, 0, _("number in %s is too large"), quote (argv[1]));
1892 /* Set globals. */
1893 from_start = t_from_start;
1894 count_lines = t_count_lines;
1895 forever = t_forever;
1897 return true;
1900 static void
1901 parse_options (int argc, char **argv,
1902 uintmax_t *n_units, enum header_mode *header_mode,
1903 double *sleep_interval)
1905 int c;
1907 while ((c = getopt_long (argc, argv, "c:n:fFqs:v0123456789",
1908 long_options, NULL))
1909 != -1)
1911 switch (c)
1913 case 'F':
1914 forever = true;
1915 follow_mode = Follow_name;
1916 reopen_inaccessible_files = true;
1917 break;
1919 case 'c':
1920 case 'n':
1921 count_lines = (c == 'n');
1922 if (*optarg == '+')
1923 from_start = true;
1924 else if (*optarg == '-')
1925 ++optarg;
1928 strtol_error s_err;
1929 s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkKmMGTPEZY0");
1930 if (s_err != LONGINT_OK)
1932 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1933 (c == 'n'
1934 ? _("invalid number of lines")
1935 : _("invalid number of bytes")));
1938 break;
1940 case 'f':
1941 case LONG_FOLLOW_OPTION:
1942 forever = true;
1943 if (optarg == NULL)
1944 follow_mode = DEFAULT_FOLLOW_MODE;
1945 else
1946 follow_mode = XARGMATCH ("--follow", optarg,
1947 follow_mode_string, follow_mode_map);
1948 break;
1950 case RETRY_OPTION:
1951 reopen_inaccessible_files = true;
1952 break;
1954 case MAX_UNCHANGED_STATS_OPTION:
1955 /* --max-unchanged-stats=N */
1956 if (xstrtoumax (optarg, NULL, 10,
1957 &max_n_unchanged_stats_between_opens,
1959 != LONGINT_OK)
1961 error (EXIT_FAILURE, 0,
1962 _("%s: invalid maximum number of unchanged stats between opens"),
1963 optarg);
1965 break;
1967 case DISABLE_INOTIFY_OPTION:
1968 disable_inotify = true;
1969 break;
1971 case PID_OPTION:
1973 strtol_error s_err;
1974 unsigned long int tmp_ulong;
1975 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1976 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1978 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1980 pid = tmp_ulong;
1982 break;
1984 case PRESUME_INPUT_PIPE_OPTION:
1985 presume_input_pipe = true;
1986 break;
1988 case 'q':
1989 *header_mode = never;
1990 break;
1992 case 's':
1994 double s;
1995 if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
1996 error (EXIT_FAILURE, 0,
1997 _("%s: invalid number of seconds"), optarg);
1998 *sleep_interval = s;
2000 break;
2002 case 'v':
2003 *header_mode = always;
2004 break;
2006 case_GETOPT_HELP_CHAR;
2008 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
2010 case '0': case '1': case '2': case '3': case '4':
2011 case '5': case '6': case '7': case '8': case '9':
2012 error (EXIT_FAILURE, 0,
2013 _("option used in invalid context -- %c"), c);
2015 default:
2016 usage (EXIT_FAILURE);
2020 if (reopen_inaccessible_files && follow_mode != Follow_name)
2021 error (0, 0, _("warning: --retry is useful mainly when following by name"));
2023 if (pid && !forever)
2024 error (0, 0,
2025 _("warning: PID ignored; --pid=PID is useful only when following"));
2026 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
2028 error (0, 0, _("warning: --pid=PID is not supported on this system"));
2029 pid = 0;
2033 /* Mark as '.ignore'd each member of F that corresponds to a
2034 pipe or fifo, and return the number of non-ignored members. */
2035 static size_t
2036 ignore_fifo_and_pipe (struct File_spec *f, size_t n_files)
2038 /* When there is no FILE operand and stdin is a pipe or FIFO
2039 POSIX requires that tail ignore the -f option.
2040 Since we allow multiple FILE operands, we extend that to say: with -f,
2041 ignore any "-" operand that corresponds to a pipe or FIFO. */
2042 size_t n_viable = 0;
2044 size_t i;
2045 for (i = 0; i < n_files; i++)
2047 bool is_a_fifo_or_pipe =
2048 (STREQ (f[i].name, "-")
2049 && !f[i].ignore
2050 && 0 <= f[i].fd
2051 && (S_ISFIFO (f[i].mode)
2052 || (HAVE_FIFO_PIPES != 1 && isapipe (f[i].fd))));
2053 if (is_a_fifo_or_pipe)
2054 f[i].ignore = true;
2055 else
2056 ++n_viable;
2059 return n_viable;
2063 main (int argc, char **argv)
2065 enum header_mode header_mode = multiple_files;
2066 bool ok = true;
2067 /* If from_start, the number of items to skip before printing; otherwise,
2068 the number of items at the end of the file to print. Although the type
2069 is signed, the value is never negative. */
2070 uintmax_t n_units = DEFAULT_N_LINES;
2071 size_t n_files;
2072 char **file;
2073 struct File_spec *F;
2074 size_t i;
2075 bool obsolete_option;
2077 /* The number of seconds to sleep between iterations.
2078 During one iteration, every file name or descriptor is checked to
2079 see if it has changed. */
2080 double sleep_interval = 1.0;
2082 initialize_main (&argc, &argv);
2083 set_program_name (argv[0]);
2084 setlocale (LC_ALL, "");
2085 bindtextdomain (PACKAGE, LOCALEDIR);
2086 textdomain (PACKAGE);
2088 atexit (close_stdout);
2090 have_read_stdin = false;
2092 count_lines = true;
2093 forever = from_start = print_headers = false;
2094 obsolete_option = parse_obsolete_option (argc, argv, &n_units);
2095 argc -= obsolete_option;
2096 argv += obsolete_option;
2097 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
2099 /* To start printing with item N_UNITS from the start of the file, skip
2100 N_UNITS - 1 items. `tail -n +0' is actually meaningless, but for Unix
2101 compatibility it's treated the same as `tail -n +1'. */
2102 if (from_start)
2104 if (n_units)
2105 --n_units;
2108 if (optind < argc)
2110 n_files = argc - optind;
2111 file = argv + optind;
2113 else
2115 static char *dummy_stdin = (char *) "-";
2116 n_files = 1;
2117 file = &dummy_stdin;
2121 bool found_hyphen = false;
2123 for (i = 0; i < n_files; i++)
2124 if (STREQ (file[i], "-"))
2125 found_hyphen = true;
2127 /* When following by name, there must be a name. */
2128 if (found_hyphen && follow_mode == Follow_name)
2129 error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quote ("-"));
2131 /* When following forever, warn if any file is `-'.
2132 This is only a warning, since tail's output (before a failing seek,
2133 and that from any non-stdin files) might still be useful. */
2134 if (forever && found_hyphen && isatty (STDIN_FILENO))
2135 error (0, 0, _("warning: following standard input"
2136 " indefinitely is ineffective"));
2139 F = xnmalloc (n_files, sizeof *F);
2140 for (i = 0; i < n_files; i++)
2141 F[i].name = file[i];
2143 if (header_mode == always
2144 || (header_mode == multiple_files && n_files > 1))
2145 print_headers = true;
2147 if (O_BINARY && ! isatty (STDOUT_FILENO))
2148 xfreopen (NULL, "wb", stdout);
2150 for (i = 0; i < n_files; i++)
2151 ok &= tail_file (&F[i], n_units);
2153 if (forever && ignore_fifo_and_pipe (F, n_files))
2155 #if HAVE_INOTIFY
2156 /* tailable_stdin() checks if the user specifies stdin via "-",
2157 or implicitly by providing no arguments. If so, we won't use inotify.
2158 Technically, on systems with a working /dev/stdin, we *could*,
2159 but would it be worth it? Verifying that it's a real device
2160 and hooked up to stdin is not trivial, while reverting to
2161 non-inotify-based tail_forever is easy and portable.
2163 any_remote_file() checks if the user has specified any
2164 files that reside on remote file systems. inotify is not used
2165 in this case because it would miss any updates to the file
2166 that were not initiated from the local system.
2168 FIXME: inotify doesn't give any notification when a new
2169 (remote) file or directory is mounted on top a watched file.
2170 When follow_mode == Follow_name we would ideally like to detect that.
2171 Note if there is a change to the original file then we'll
2172 recheck it and follow the new file, or ignore it if the
2173 file has changed to being remote.
2175 FIXME: when using inotify, and a directory for a watched file
2176 is recreated, then we don't recheck any new file when
2177 follow_mode == Follow_name */
2178 if (!disable_inotify && (tailable_stdin (F, n_files)
2179 || any_remote_file (F, n_files)))
2180 disable_inotify = true;
2182 if (!disable_inotify)
2184 int wd = inotify_init ();
2185 if (0 <= wd)
2187 /* Flush any output from tail_file, now, since
2188 tail_forever_inotify flushes only after writing,
2189 not before reading. */
2190 if (fflush (stdout) != 0)
2191 error (EXIT_FAILURE, errno, _("write error"));
2193 if (!tail_forever_inotify (wd, F, n_files, sleep_interval))
2194 exit (EXIT_FAILURE);
2196 error (0, errno, _("inotify cannot be used, reverting to polling"));
2198 #endif
2199 disable_inotify = true;
2200 tail_forever (F, n_files, sleep_interval);
2203 if (have_read_stdin && close (STDIN_FILENO) < 0)
2204 error (EXIT_FAILURE, errno, "-");
2205 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);