1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989-2016 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
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>. */
31 #include <sys/types.h>
43 #include "safe-read.h"
44 #include "stat-size.h"
45 #include "stat-time.h"
47 #include "xnanosleep.h"
48 #include "xdectoint.h"
54 # include <sys/inotify.h>
55 /* 'select' is used by tail_forever_inotify. */
56 # include <sys/select.h>
58 /* inotify needs to know if a file is local. */
60 # include "fs-is-local.h"
61 # if HAVE_SYS_STATFS_H
62 # include <sys/statfs.h>
68 /* The official name of this program (e.g., no 'g' prefix). */
69 #define PROGRAM_NAME "tail"
72 proper_name ("Paul Rubin"), \
73 proper_name ("David MacKenzie"), \
74 proper_name ("Ian Lance Taylor"), \
75 proper_name ("Jim Meyering")
77 /* Number of items to tail. */
78 #define DEFAULT_N_LINES 10
80 /* Special values for dump_remainder's N_BYTES parameter. */
81 #define COPY_TO_EOF UINTMAX_MAX
82 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
84 /* FIXME: make Follow_name the default? */
85 #define DEFAULT_FOLLOW_MODE Follow_descriptor
89 /* Follow the name of each file: if the file is renamed, try to reopen
90 that name and track the end of the new file if/when it's recreated.
91 This is useful for tracking logs that are occasionally rotated. */
94 /* Follow each descriptor obtained upon opening a file.
95 That means we'll continue to follow the end of a file even after
96 it has been renamed or unlinked. */
100 /* The types of files for which tail works. */
101 #define IS_TAILABLE_FILE_TYPE(Mode) \
102 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
104 static char const *const follow_mode_string
[] =
106 "descriptor", "name", NULL
109 static enum Follow_mode
const follow_mode_map
[] =
111 Follow_descriptor
, Follow_name
,
116 /* The actual file name, or "-" for stdin. */
119 /* Attributes of the file the last time we checked. */
121 struct timespec mtime
;
126 /* The specified name initially referred to a directory or some other
127 type for which tail isn't meaningful. Unlike for a permission problem
128 (tailable, below) once this is set, the name is not checked ever again. */
131 /* See the description of fremote. */
134 /* A file is tailable if it exists, is readable, and is of type
135 IS_TAILABLE_FILE_TYPE. */
138 /* File descriptor on which the file is open; -1 if it's not open. */
141 /* The value of errno seen last time we checked this file. */
144 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
148 /* The watch descriptor used by inotify. */
151 /* The parent directory watch descriptor. It is used only
152 * when Follow_name is used. */
155 /* Offset in NAME of the basename part. */
156 size_t basename_start
;
159 /* See description of DEFAULT_MAX_N_... below. */
160 uintmax_t n_unchanged_stats
;
163 /* Keep trying to open a file even if it is inaccessible when tail starts
164 or if it becomes inaccessible later -- useful only with -f. */
165 static bool reopen_inaccessible_files
;
167 /* If true, interpret the numeric argument as the number of lines.
168 Otherwise, interpret it as the number of bytes. */
169 static bool count_lines
;
171 /* Whether we follow the name of each file or the file descriptor
172 that is initially associated with each name. */
173 static enum Follow_mode follow_mode
= Follow_descriptor
;
175 /* If true, read from the ends of all specified files until killed. */
178 /* If true, count from start of file instead of end. */
179 static bool from_start
;
181 /* If true, print filename headers. */
182 static bool print_headers
;
184 /* Character to split lines by. */
185 static char line_end
;
187 /* When to print the filename banners. */
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. */
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. */
221 RETRY_OPTION
= CHAR_MAX
+ 1,
222 MAX_UNCHANGED_STATS_OPTION
,
224 PRESUME_INPUT_PIPE_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 {"zero-terminated", no_argument
, NULL
, 'z'},
246 {GETOPT_HELP_OPTION_DECL
},
247 {GETOPT_VERSION_OPTION_DECL
},
254 if (status
!= EXIT_SUCCESS
)
259 Usage: %s [OPTION]... [FILE]...\n\
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 "), DEFAULT_N_LINES
);
268 emit_mandatory_arg_note ();
271 -c, --bytes=[+]NUM output the last NUM bytes; or use -c +NUM to\n\
272 output starting with byte NUM of each file\n\
275 -f, --follow[={name|descriptor}]\n\
276 output appended data as the file grows;\n\
277 an absent option argument means 'descriptor'\n\
278 -F same as --follow=name --retry\n\
281 -n, --lines=[+]NUM output the last NUM lines, instead of the last %d;\n\
282 or use -n +NUM to output starting with line NUM\n\
283 --max-unchanged-stats=N\n\
284 with --follow=name, reopen a FILE which has not\n\
285 changed size after N (default %d) iterations\n\
286 to see if it has been unlinked or renamed\n\
287 (this is the usual case of rotated log files);\n\
288 with inotify, this option is rarely useful\n\
291 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
294 --pid=PID with -f, terminate after process ID, PID dies\n\
295 -q, --quiet, --silent never output headers giving file names\n\
296 --retry keep trying to open a file if it is inaccessible\n\
299 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
300 (default 1.0) between iterations;\n\
301 with inotify and --pid=P, check process P at\n\
302 least once every N seconds\n\
303 -v, --verbose always output headers giving file names\n\
306 -z, --zero-terminated line delimiter is NUL, not newline\n\
308 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
309 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
312 NUM 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\
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\
325 emit_ancillary_info (PROGRAM_NAME
);
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));
338 pretty_name (struct File_spec
const *f
)
340 return (STREQ (f
->name
, "-") ? _("standard input") : f
->name
);
343 /* Record a file F with descriptor FD, size SIZE, status ST, and
344 blocking status BLOCKING. */
347 record_open_fd (struct File_spec
*f
, int fd
,
348 off_t size
, struct stat
const *st
,
353 f
->mtime
= get_stat_mtime (st
);
356 f
->mode
= st
->st_mode
;
357 f
->blocking
= blocking
;
358 f
->n_unchanged_stats
= 0;
362 /* Close the file with descriptor FD and name FILENAME. */
365 close_fd (int fd
, const char *filename
)
367 if (fd
!= -1 && fd
!= STDIN_FILENO
&& close (fd
))
369 error (0, errno
, _("closing %s (fd=%d)"), quoteaf (filename
), fd
);
374 write_header (const char *pretty_filename
)
376 static bool first_file
= true;
378 printf ("%s==> %s <==\n", (first_file
? "" : "\n"), pretty_filename
);
382 /* Write N_BYTES from BUFFER to stdout.
383 Exit immediately on error with a single diagnostic. */
386 xwrite_stdout (char const *buffer
, size_t n_bytes
)
388 if (n_bytes
> 0 && fwrite (buffer
, 1, n_bytes
, stdout
) < n_bytes
)
390 clearerr (stdout
); /* To avoid redundant close_stdout diagnostic. */
391 die (EXIT_FAILURE
, errno
, _("error writing %s"),
392 quoteaf ("standard output"));
396 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
397 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
398 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
399 Return the number of bytes read from the file. */
402 dump_remainder (const char *pretty_filename
, int fd
, uintmax_t n_bytes
)
405 uintmax_t n_remaining
= n_bytes
;
411 size_t n
= MIN (n_remaining
, BUFSIZ
);
412 size_t bytes_read
= safe_read (fd
, buffer
, n
);
413 if (bytes_read
== SAFE_READ_ERROR
)
416 die (EXIT_FAILURE
, errno
, _("error reading %s"),
417 quoteaf (pretty_filename
));
422 xwrite_stdout (buffer
, bytes_read
);
423 n_written
+= bytes_read
;
424 if (n_bytes
!= COPY_TO_EOF
)
426 n_remaining
-= bytes_read
;
427 if (n_remaining
== 0 || n_bytes
== COPY_A_BUFFER
)
435 /* Call lseek with the specified arguments, where file descriptor FD
436 corresponds to the file, FILENAME.
437 Give a diagnostic and exit nonzero if lseek fails.
438 Otherwise, return the resulting offset. */
441 xlseek (int fd
, off_t offset
, int whence
, char const *filename
)
443 off_t new_offset
= lseek (fd
, offset
, whence
);
444 char buf
[INT_BUFSIZE_BOUND (offset
)];
450 s
= offtostr (offset
, buf
);
454 error (0, errno
, _("%s: cannot seek to offset %s"),
455 quotef (filename
), s
);
458 error (0, errno
, _("%s: cannot seek to relative offset %s"),
459 quotef (filename
), s
);
462 error (0, errno
, _("%s: cannot seek to end-relative offset %s"),
463 quotef (filename
), s
);
472 /* Print the last N_LINES lines from the end of file FD.
473 Go backward through the file, reading 'BUFSIZ' bytes at a time (except
474 probably the first), until we hit the start of the file or have
475 read NUMBER newlines.
476 START_POS is the starting position of the read pointer for the file
477 associated with FD (may be nonzero).
478 END_POS is the file offset of EOF (one larger than offset of last byte).
479 Return true if successful. */
482 file_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
483 off_t start_pos
, off_t end_pos
, uintmax_t *read_pos
)
492 /* Set 'bytes_read' to the size of the last, probably partial, buffer;
493 0 < 'bytes_read' <= 'BUFSIZ'. */
494 bytes_read
= (pos
- start_pos
) % BUFSIZ
;
497 /* Make 'pos' a multiple of 'BUFSIZ' (0 if the file is short), so that all
498 reads will be on block boundaries, which might increase efficiency. */
500 xlseek (fd
, pos
, SEEK_SET
, pretty_filename
);
501 bytes_read
= safe_read (fd
, buffer
, bytes_read
);
502 if (bytes_read
== SAFE_READ_ERROR
)
504 error (0, errno
, _("error reading %s"), quoteaf (pretty_filename
));
507 *read_pos
= pos
+ bytes_read
;
509 /* Count the incomplete line on files that don't end with a newline. */
510 if (bytes_read
&& buffer
[bytes_read
- 1] != line_end
)
515 /* Scan backward, counting the newlines in this bufferfull. */
517 size_t n
= bytes_read
;
521 nl
= memrchr (buffer
, line_end
, n
);
527 /* If this newline isn't the last character in the buffer,
528 output the part that is after it. */
529 if (n
!= bytes_read
- 1)
530 xwrite_stdout (nl
+ 1, bytes_read
- (n
+ 1));
531 *read_pos
+= dump_remainder (pretty_filename
, fd
,
532 end_pos
- (pos
+ bytes_read
));
537 /* Not enough newlines in that bufferfull. */
538 if (pos
== start_pos
)
540 /* Not enough lines in the file; print everything from
541 start_pos to the end. */
542 xlseek (fd
, start_pos
, SEEK_SET
, pretty_filename
);
543 *read_pos
= start_pos
+ dump_remainder (pretty_filename
, fd
,
548 xlseek (fd
, pos
, SEEK_SET
, pretty_filename
);
550 bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
551 if (bytes_read
== SAFE_READ_ERROR
)
553 error (0, errno
, _("error reading %s"), quoteaf (pretty_filename
));
557 *read_pos
= pos
+ bytes_read
;
559 while (bytes_read
> 0);
564 /* Print the last N_LINES lines from the end of the standard input,
565 open for reading as pipe FD.
566 Buffer the text as a linked list of LBUFFERs, adding them as needed.
567 Return true if successful. */
570 pipe_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
578 struct linebuffer
*next
;
580 typedef struct linebuffer LBUFFER
;
581 LBUFFER
*first
, *last
, *tmp
;
582 size_t total_lines
= 0; /* Total number of newlines in all buffers. */
584 size_t n_read
; /* Size in bytes of most recent read */
586 first
= last
= xmalloc (sizeof (LBUFFER
));
587 first
->nbytes
= first
->nlines
= 0;
589 tmp
= xmalloc (sizeof (LBUFFER
));
591 /* Input is always read into a fresh buffer. */
594 n_read
= safe_read (fd
, tmp
->buffer
, BUFSIZ
);
595 if (n_read
== 0 || n_read
== SAFE_READ_ERROR
)
597 tmp
->nbytes
= n_read
;
602 /* Count the number of newlines just read. */
604 char const *buffer_end
= tmp
->buffer
+ n_read
;
605 char const *p
= tmp
->buffer
;
606 while ((p
= memchr (p
, line_end
, buffer_end
- p
)))
612 total_lines
+= tmp
->nlines
;
614 /* If there is enough room in the last buffer read, just append the new
615 one to it. This is because when reading from a pipe, 'n_read' can
616 often be very small. */
617 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
619 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
620 last
->nbytes
+= tmp
->nbytes
;
621 last
->nlines
+= tmp
->nlines
;
625 /* If there's not enough room, link the new buffer onto the end of
626 the list, then either free up the oldest buffer for the next
627 read if that would leave enough lines, or else malloc a new one.
628 Some compaction mechanism is possible but probably not
630 last
= last
->next
= tmp
;
631 if (total_lines
- first
->nlines
> n_lines
)
634 total_lines
-= first
->nlines
;
638 tmp
= xmalloc (sizeof (LBUFFER
));
644 if (n_read
== SAFE_READ_ERROR
)
646 error (0, errno
, _("error reading %s"), quoteaf (pretty_filename
));
651 /* If the file is empty, then bail out. */
652 if (last
->nbytes
== 0)
655 /* This prevents a core dump when the pipe contains no newlines. */
659 /* Count the incomplete line on files that don't end with a newline. */
660 if (last
->buffer
[last
->nbytes
- 1] != line_end
)
666 /* Run through the list, printing lines. First, skip over unneeded
668 for (tmp
= first
; total_lines
- tmp
->nlines
> n_lines
; tmp
= tmp
->next
)
669 total_lines
-= tmp
->nlines
;
671 /* Find the correct beginning, then print the rest of the file. */
673 char const *beg
= tmp
->buffer
;
674 char const *buffer_end
= tmp
->buffer
+ tmp
->nbytes
;
675 if (total_lines
> n_lines
)
677 /* Skip 'total_lines' - 'n_lines' newlines. We made sure that
678 'total_lines' - 'n_lines' <= 'tmp->nlines'. */
680 for (j
= total_lines
- n_lines
; j
; --j
)
682 beg
= memchr (beg
, line_end
, buffer_end
- beg
);
688 xwrite_stdout (beg
, buffer_end
- beg
);
691 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
692 xwrite_stdout (tmp
->buffer
, tmp
->nbytes
);
704 /* Print the last N_BYTES characters from the end of pipe FD.
705 This is a stripped down version of pipe_lines.
706 Return true if successful. */
709 pipe_bytes (const char *pretty_filename
, int fd
, uintmax_t n_bytes
,
716 struct charbuffer
*next
;
718 typedef struct charbuffer CBUFFER
;
719 CBUFFER
*first
, *last
, *tmp
;
720 size_t i
; /* Index into buffers. */
721 size_t total_bytes
= 0; /* Total characters in all buffers. */
725 first
= last
= xmalloc (sizeof (CBUFFER
));
728 tmp
= xmalloc (sizeof (CBUFFER
));
730 /* Input is always read into a fresh buffer. */
733 n_read
= safe_read (fd
, tmp
->buffer
, BUFSIZ
);
734 if (n_read
== 0 || n_read
== SAFE_READ_ERROR
)
737 tmp
->nbytes
= n_read
;
740 total_bytes
+= tmp
->nbytes
;
741 /* If there is enough room in the last buffer read, just append the new
742 one to it. This is because when reading from a pipe, 'nbytes' can
743 often be very small. */
744 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
746 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
747 last
->nbytes
+= tmp
->nbytes
;
751 /* If there's not enough room, link the new buffer onto the end of
752 the list, then either free up the oldest buffer for the next
753 read if that would leave enough characters, or else malloc a new
754 one. Some compaction mechanism is possible but probably not
756 last
= last
->next
= tmp
;
757 if (total_bytes
- first
->nbytes
> n_bytes
)
760 total_bytes
-= first
->nbytes
;
765 tmp
= xmalloc (sizeof (CBUFFER
));
772 if (n_read
== SAFE_READ_ERROR
)
774 error (0, errno
, _("error reading %s"), quoteaf (pretty_filename
));
779 /* Run through the list, printing characters. First, skip over unneeded
781 for (tmp
= first
; total_bytes
- tmp
->nbytes
> n_bytes
; tmp
= tmp
->next
)
782 total_bytes
-= tmp
->nbytes
;
784 /* Find the correct beginning, then print the rest of the file.
785 We made sure that 'total_bytes' - 'n_bytes' <= 'tmp->nbytes'. */
786 if (total_bytes
> n_bytes
)
787 i
= total_bytes
- n_bytes
;
790 xwrite_stdout (&tmp
->buffer
[i
], tmp
->nbytes
- i
);
792 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
793 xwrite_stdout (tmp
->buffer
, tmp
->nbytes
);
805 /* Skip N_BYTES characters from the start of pipe FD, and print
806 any extra characters that were read beyond that.
807 Return 1 on error, 0 if ok, -1 if EOF. */
810 start_bytes (const char *pretty_filename
, int fd
, uintmax_t n_bytes
,
817 size_t bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
820 if (bytes_read
== SAFE_READ_ERROR
)
822 error (0, errno
, _("error reading %s"), quoteaf (pretty_filename
));
825 *read_pos
+= bytes_read
;
826 if (bytes_read
<= n_bytes
)
827 n_bytes
-= bytes_read
;
830 size_t n_remaining
= bytes_read
- n_bytes
;
832 xwrite_stdout (&buffer
[n_bytes
], n_remaining
);
840 /* Skip N_LINES lines at the start of file or pipe FD, and print
841 any extra characters that were read beyond that.
842 Return 1 on error, 0 if ok, -1 if EOF. */
845 start_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
854 size_t bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
855 if (bytes_read
== 0) /* EOF */
857 if (bytes_read
== SAFE_READ_ERROR
) /* error */
859 error (0, errno
, _("error reading %s"), quoteaf (pretty_filename
));
863 char *buffer_end
= buffer
+ bytes_read
;
865 *read_pos
+= bytes_read
;
868 while ((p
= memchr (p
, line_end
, buffer_end
- p
)))
874 xwrite_stdout (p
, buffer_end
- p
);
881 /* Return false when FD is open on a file residing on a local file system.
882 If fstatfs fails, give a diagnostic and return true.
883 If fstatfs cannot be called, return true. */
885 fremote (int fd
, const char *name
)
887 bool remote
= true; /* be conservative (poll by default). */
889 #if HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE && defined __linux__
891 int err
= fstatfs (fd
, &buf
);
894 /* On at least linux-2.6.38, fstatfs fails with ENOSYS when FD
895 is open on a pipe. Treat that like a remote file. */
897 error (0, errno
, _("cannot determine location of %s. "
898 "reverting to polling"), quoteaf (name
));
902 switch (is_local_fs_type (buf
.f_type
))
907 /* Treat unrecognized file systems as "remote", so caller polls.
908 Note README-release has instructions for syncing the internal
909 list with the latest Linux kernel file system constants. */
915 assert (!"unexpected return value from is_local_fs_type");
923 /* open/fstat F->name and handle changes. */
925 recheck (struct File_spec
*f
, bool blocking
)
927 struct stat new_stats
;
929 bool is_stdin
= (STREQ (f
->name
, "-"));
930 bool was_tailable
= f
->tailable
;
931 int prev_errnum
= f
->errnum
;
935 : open (f
->name
, O_RDONLY
| (blocking
? 0 : O_NONBLOCK
)));
937 assert (valid_file_spec (f
));
939 /* If the open fails because the file doesn't exist,
940 then mark the file as not tailable. */
941 f
->tailable
= !(reopen_inaccessible_files
&& fd
== -1);
943 if (! disable_inotify
&& ! lstat (f
->name
, &new_stats
)
944 && S_ISLNK (new_stats
.st_mode
))
946 /* Diagnose the edge case where a regular file is changed
947 to a symlink. We avoid inotify with symlinks since
948 it's awkward to match between symlink name and target. */
953 error (0, 0, _("%s has been replaced with an untailable symbolic link"),
954 quoteaf (pretty_name (f
)));
956 else if (fd
== -1 || fstat (fd
, &new_stats
) < 0)
964 /* FIXME-maybe: detect the case in which the file first becomes
965 unreadable (perms), and later becomes readable again and can
966 be seen to be the same file (dev/ino). Otherwise, tail prints
967 the entire contents of the file when it becomes readable. */
968 error (0, f
->errnum
, _("%s has become inaccessible"),
969 quoteaf (pretty_name (f
)));
973 /* say nothing... it's still not tailable */
976 else if (prev_errnum
!= errno
)
977 error (0, errno
, "%s", quotef (pretty_name (f
)));
979 else if (!IS_TAILABLE_FILE_TYPE (new_stats
.st_mode
))
984 if (! (reopen_inaccessible_files
&& follow_mode
== Follow_name
))
986 if (was_tailable
|| prev_errnum
!= f
->errnum
)
987 error (0, 0, _("%s has been replaced with an untailable file%s"),
988 quoteaf (pretty_name (f
)),
989 f
->ignore
? _("; giving up on this name") : "");
991 else if ((f
->remote
= fremote (fd
, pretty_name (f
))) && ! disable_inotify
)
995 error (0, 0, _("%s has been replaced with an untailable remote file"),
996 quoteaf (pretty_name (f
)));
1008 close_fd (fd
, pretty_name (f
));
1009 close_fd (f
->fd
, pretty_name (f
));
1012 else if (prev_errnum
&& prev_errnum
!= ENOENT
)
1015 assert (f
->fd
== -1);
1016 error (0, 0, _("%s has become accessible"), quoteaf (pretty_name (f
)));
1018 else if (f
->fd
== -1)
1020 /* A new file even when inodes haven't changed as <dev,inode>
1021 pairs can be reused, and we know the file was missing
1022 on the previous iteration. Note this also means the file
1023 is redisplayed in --follow=name mode if renamed away from
1024 and back to a monitored name. */
1028 _("%s has appeared; following new file"),
1029 quoteaf (pretty_name (f
)));
1031 else if (f
->ino
!= new_stats
.st_ino
|| f
->dev
!= new_stats
.st_dev
)
1033 /* File has been replaced (e.g., via log rotation) --
1034 tail the new one. */
1038 _("%s has been replaced; following new file"),
1039 quoteaf (pretty_name (f
)));
1041 /* Close the old one. */
1042 close_fd (f
->fd
, pretty_name (f
));
1047 /* No changes detected, so close new fd. */
1048 close_fd (fd
, pretty_name (f
));
1051 /* FIXME: When a log is rotated, daemons tend to log to the
1052 old file descriptor until the new file is present and
1053 the daemon is sent a signal. Therefore tail may miss entries
1054 being written to the old file. Perhaps we should keep
1055 the older file open and continue to monitor it until
1056 data is written to a new file. */
1059 /* Start at the beginning of the file. */
1060 record_open_fd (f
, fd
, 0, &new_stats
, (is_stdin
? -1 : blocking
));
1061 xlseek (fd
, 0, SEEK_SET
, pretty_name (f
));
1065 /* Return true if any of the N_FILES files in F are live, i.e., have
1066 open file descriptors, or should be checked again (see --retry).
1067 When following descriptors, checking should only continue when any
1068 of the files is not yet ignored. */
1071 any_live_files (const struct File_spec
*f
, size_t n_files
)
1075 /* In inotify mode, ignore may be set for files
1076 which may later be replaced with new files.
1077 So always consider files live in -F mode. */
1078 if (reopen_inaccessible_files
&& follow_mode
== Follow_name
)
1081 for (i
= 0; i
< n_files
; i
++)
1087 if (! f
[i
].ignore
&& reopen_inaccessible_files
)
1095 /* Tail N_FILES files forever, or until killed.
1096 The pertinent information for each file is stored in an entry of F.
1097 Loop over each of them, doing an fstat to see if they have changed size,
1098 and an occasional open/fstat to see if any dev/ino pair has changed.
1099 If none of them have changed size in one iteration, sleep for a
1100 while and try again. Continue until the user interrupts us. */
1103 tail_forever (struct File_spec
*f
, size_t n_files
, double sleep_interval
)
1105 /* Use blocking I/O as an optimization, when it's easy. */
1106 bool blocking
= (pid
== 0 && follow_mode
== Follow_descriptor
1107 && n_files
== 1 && f
[0].fd
!= -1 && ! S_ISREG (f
[0].mode
));
1109 bool writer_is_dead
= false;
1116 bool any_input
= false;
1118 for (i
= 0; i
< n_files
; i
++)
1124 uintmax_t bytes_read
;
1131 recheck (&f
[i
], blocking
);
1136 name
= pretty_name (&f
[i
]);
1139 if (f
[i
].blocking
!= blocking
)
1141 int old_flags
= fcntl (fd
, F_GETFL
);
1142 int new_flags
= old_flags
| (blocking
? 0 : O_NONBLOCK
);
1144 || (new_flags
!= old_flags
1145 && fcntl (fd
, F_SETFL
, new_flags
) == -1))
1147 /* Don't update f[i].blocking if fcntl fails. */
1148 if (S_ISREG (f
[i
].mode
) && errno
== EPERM
)
1150 /* This happens when using tail -f on a file with
1151 the append-only attribute. */
1154 die (EXIT_FAILURE
, errno
,
1155 _("%s: cannot change nonblocking mode"),
1159 f
[i
].blocking
= blocking
;
1164 if (fstat (fd
, &stats
) != 0)
1167 f
[i
].errnum
= errno
;
1168 error (0, errno
, "%s", quotef (name
));
1169 close (fd
); /* ignore failure */
1173 if (f
[i
].mode
== stats
.st_mode
1174 && (! S_ISREG (stats
.st_mode
) || f
[i
].size
== stats
.st_size
)
1175 && timespec_cmp (f
[i
].mtime
, get_stat_mtime (&stats
)) == 0)
1177 if ((max_n_unchanged_stats_between_opens
1178 <= f
[i
].n_unchanged_stats
++)
1179 && follow_mode
== Follow_name
)
1181 recheck (&f
[i
], f
[i
].blocking
);
1182 f
[i
].n_unchanged_stats
= 0;
1187 /* This file has changed. Print out what we can, and
1188 then keep looping. */
1190 f
[i
].mtime
= get_stat_mtime (&stats
);
1191 f
[i
].mode
= stats
.st_mode
;
1194 f
[i
].n_unchanged_stats
= 0;
1196 /* XXX: This is only a heuristic, as the file may have also
1197 been truncated and written to if st_size >= size
1198 (in which case we ignore new data <= size). */
1199 if (S_ISREG (mode
) && stats
.st_size
< f
[i
].size
)
1201 error (0, 0, _("%s: file truncated"), quotef (name
));
1202 /* Assume the file was truncated to 0,
1203 and therefore output all "new" data. */
1204 xlseek (fd
, 0, SEEK_SET
, name
);
1211 write_header (name
);
1216 /* Don't read more than st_size on networked file systems
1217 because it was seen on glusterfs at least, that st_size
1218 may be smaller than the data read on a _subsequent_ stat call. */
1219 uintmax_t bytes_to_read
;
1221 bytes_to_read
= COPY_A_BUFFER
;
1222 else if (S_ISREG (mode
) && f
[i
].remote
)
1223 bytes_to_read
= stats
.st_size
- f
[i
].size
;
1225 bytes_to_read
= COPY_TO_EOF
;
1227 bytes_read
= dump_remainder (name
, fd
, bytes_to_read
);
1229 any_input
|= (bytes_read
!= 0);
1230 f
[i
].size
+= bytes_read
;
1233 if (! any_live_files (f
, n_files
))
1235 error (0, 0, _("no files remaining"));
1239 if ((!any_input
|| blocking
) && fflush (stdout
) != 0)
1240 die (EXIT_FAILURE
, errno
, _("write error"));
1242 /* If nothing was read, sleep and/or check for dead writers. */
1248 /* Once the writer is dead, read the files once more to
1249 avoid a race condition. */
1250 writer_is_dead
= (pid
!= 0
1251 && kill (pid
, 0) != 0
1252 /* Handle the case in which you cannot send a
1253 signal to the writer, so kill fails and sets
1257 if (!writer_is_dead
&& xnanosleep (sleep_interval
))
1258 die (EXIT_FAILURE
, errno
, _("cannot read realtime clock"));
1266 /* Return true if any of the N_FILES files in F is remote, i.e., has
1267 an open file descriptor and is on a network file system. */
1270 any_remote_file (const struct File_spec
*f
, size_t n_files
)
1274 for (i
= 0; i
< n_files
; i
++)
1275 if (0 <= f
[i
].fd
&& f
[i
].remote
)
1280 /* Return true if any of the N_FILES files in F is non remote, i.e., has
1281 an open file descriptor and is not on a network file system. */
1284 any_non_remote_file (const struct File_spec
*f
, size_t n_files
)
1288 for (i
= 0; i
< n_files
; i
++)
1289 if (0 <= f
[i
].fd
&& ! f
[i
].remote
)
1294 /* Return true if any of the N_FILES files in F is a symlink.
1295 Note we don't worry about the edge case where "-" exists,
1296 since that will have the same consequences for inotify,
1297 which is the only context this function is currently used. */
1300 any_symlinks (const struct File_spec
*f
, size_t n_files
)
1305 for (i
= 0; i
< n_files
; i
++)
1306 if (lstat (f
[i
].name
, &st
) == 0 && S_ISLNK (st
.st_mode
))
1311 /* Return true if any of the N_FILES files in F represents
1312 stdin and is tailable. */
1315 tailable_stdin (const struct File_spec
*f
, size_t n_files
)
1319 for (i
= 0; i
< n_files
; i
++)
1320 if (!f
[i
].ignore
&& STREQ (f
[i
].name
, "-"))
1326 wd_hasher (const void *entry
, size_t tabsize
)
1328 const struct File_spec
*spec
= entry
;
1329 return spec
->wd
% tabsize
;
1333 wd_comparator (const void *e1
, const void *e2
)
1335 const struct File_spec
*spec1
= e1
;
1336 const struct File_spec
*spec2
= e2
;
1337 return spec1
->wd
== spec2
->wd
;
1340 /* Output (new) data for FSPEC->fd. */
1342 check_fspec (struct File_spec
*fspec
, struct File_spec
**prev_fspec
)
1347 if (fspec
->fd
== -1)
1350 name
= pretty_name (fspec
);
1352 if (fstat (fspec
->fd
, &stats
) != 0)
1354 fspec
->errnum
= errno
;
1355 close_fd (fspec
->fd
, name
);
1360 /* XXX: This is only a heuristic, as the file may have also
1361 been truncated and written to if st_size >= size
1362 (in which case we ignore new data <= size).
1363 Though in the inotify case it's more likely we'll get
1364 separate events for truncate() and write(). */
1365 if (S_ISREG (fspec
->mode
) && stats
.st_size
< fspec
->size
)
1367 error (0, 0, _("%s: file truncated"), quotef (name
));
1368 xlseek (fspec
->fd
, 0, SEEK_SET
, name
);
1371 else if (S_ISREG (fspec
->mode
) && stats
.st_size
== fspec
->size
1372 && timespec_cmp (fspec
->mtime
, get_stat_mtime (&stats
)) == 0)
1375 if (fspec
!= *prev_fspec
)
1378 write_header (name
);
1379 *prev_fspec
= fspec
;
1382 uintmax_t bytes_read
= dump_remainder (name
, fspec
->fd
, COPY_TO_EOF
);
1383 fspec
->size
+= bytes_read
;
1385 if (fflush (stdout
) != 0)
1386 die (EXIT_FAILURE
, errno
, _("write error"));
1389 /* Attempt to tail N_FILES files forever, or until killed.
1390 Check modifications using the inotify events system.
1391 Return false on error, or true to revert to polling. */
1393 tail_forever_inotify (int wd
, struct File_spec
*f
, size_t n_files
,
1394 double sleep_interval
)
1396 # if TAIL_TEST_SLEEP
1397 /* Delay between open() and inotify_add_watch()
1398 to help trigger different cases. */
1399 xnanosleep (1000000);
1401 unsigned int max_realloc
= 3;
1403 /* Map an inotify watch descriptor to the name of the file it's watching. */
1404 Hash_table
*wd_to_name
;
1406 bool found_watchable_file
= false;
1407 bool tailed_but_unwatchable
= false;
1408 bool found_unwatchable_dir
= false;
1409 bool no_inotify_resources
= false;
1410 bool writer_is_dead
= false;
1411 struct File_spec
*prev_fspec
;
1414 size_t evbuf_off
= 0;
1417 wd_to_name
= hash_initialize (n_files
, NULL
, wd_hasher
, wd_comparator
, NULL
);
1421 /* The events mask used with inotify on files (not directories). */
1422 uint32_t inotify_wd_mask
= IN_MODIFY
;
1423 /* TODO: Perhaps monitor these events in Follow_descriptor mode also,
1424 to tag reported file names with "deleted", "moved" etc. */
1425 if (follow_mode
== Follow_name
)
1426 inotify_wd_mask
|= (IN_ATTRIB
| IN_DELETE_SELF
| IN_MOVE_SELF
);
1428 /* Add an inotify watch for each watched file. If -F is specified then watch
1429 its parent directory too, in this way when they re-appear we can add them
1430 again to the watch list. */
1432 for (i
= 0; i
< n_files
; i
++)
1436 size_t fnlen
= strlen (f
[i
].name
);
1442 if (follow_mode
== Follow_name
)
1444 size_t dirlen
= dir_len (f
[i
].name
);
1445 char prev
= f
[i
].name
[dirlen
];
1446 f
[i
].basename_start
= last_component (f
[i
].name
) - f
[i
].name
;
1448 f
[i
].name
[dirlen
] = '\0';
1450 /* It's fine to add the same directory more than once.
1451 In that case the same watch descriptor is returned. */
1452 f
[i
].parent_wd
= inotify_add_watch (wd
, dirlen
? f
[i
].name
: ".",
1453 (IN_CREATE
| IN_DELETE
1454 | IN_MOVED_TO
| IN_ATTRIB
));
1456 f
[i
].name
[dirlen
] = prev
;
1458 if (f
[i
].parent_wd
< 0)
1460 if (errno
!= ENOSPC
) /* suppress confusing error. */
1461 error (0, errno
, _("cannot watch parent directory of %s"),
1462 quoteaf (f
[i
].name
));
1464 error (0, 0, _("inotify resources exhausted"));
1465 found_unwatchable_dir
= true;
1466 /* We revert to polling below. Note invalid uses
1467 of the inotify API will still be diagnosed. */
1472 f
[i
].wd
= inotify_add_watch (wd
, f
[i
].name
, inotify_wd_mask
);
1476 if (f
[i
].fd
!= -1) /* already tailed. */
1477 tailed_but_unwatchable
= true;
1478 if (errno
== ENOSPC
|| errno
== ENOMEM
)
1480 no_inotify_resources
= true;
1481 error (0, 0, _("inotify resources exhausted"));
1484 else if (errno
!= f
[i
].errnum
)
1485 error (0, errno
, _("cannot watch %s"), quoteaf (f
[i
].name
));
1489 if (hash_insert (wd_to_name
, &(f
[i
])) == NULL
)
1492 found_watchable_file
= true;
1496 /* Linux kernel 2.6.24 at least has a bug where eventually, ENOSPC is always
1497 returned by inotify_add_watch. In any case we should revert to polling
1498 when there are no inotify resources. Also a specified directory may not
1499 be currently present or accessible, so revert to polling. Also an already
1500 tailed but unwatchable due rename/unlink race, should also revert. */
1501 if (no_inotify_resources
|| found_unwatchable_dir
1502 || (follow_mode
== Follow_descriptor
&& tailed_but_unwatchable
))
1504 hash_free (wd_to_name
);
1509 if (follow_mode
== Follow_descriptor
&& !found_watchable_file
)
1512 prev_fspec
= &(f
[n_files
- 1]);
1514 /* Check files again. New files or data can be available since last time we
1515 checked and before they are watched by inotify. */
1516 for (i
= 0; i
< n_files
; i
++)
1520 /* check for new files. */
1521 if (follow_mode
== Follow_name
)
1522 recheck (&(f
[i
]), false);
1523 else if (f
[i
].fd
!= -1)
1525 /* If the file was replaced in the small window since we tailed,
1526 then assume the watch is on the wrong item (different to
1527 that we've already produced output for), and so revert to
1528 polling the original descriptor. */
1531 if (stat (f
[i
].name
, &stats
) == 0
1532 && (f
[i
].dev
!= stats
.st_dev
|| f
[i
].ino
!= stats
.st_ino
))
1534 error (0, errno
, _("%s was replaced"),
1535 quoteaf (pretty_name (&(f
[i
]))));
1536 hash_free (wd_to_name
);
1543 /* check for new data. */
1544 check_fspec (&f
[i
], &prev_fspec
);
1548 evlen
+= sizeof (struct inotify_event
) + 1;
1549 evbuf
= xmalloc (evlen
);
1551 /* Wait for inotify events and handle them. Events on directories
1552 ensure that watched files can be re-added when following by name.
1553 This loop blocks on the 'safe_read' call until a new event is notified.
1554 But when --pid=P is specified, tail usually waits via the select. */
1557 struct File_spec
*fspec
;
1558 struct inotify_event
*ev
;
1561 /* When following by name without --retry, and the last file has
1562 been unlinked or renamed-away, diagnose it and return. */
1563 if (follow_mode
== Follow_name
1564 && ! reopen_inaccessible_files
1565 && hash_get_n_entries (wd_to_name
) == 0)
1567 error (0, 0, _("no files remaining"));
1571 /* When watching a PID, ensure that a read from WD will not block
1576 exit (EXIT_SUCCESS
);
1578 writer_is_dead
= (kill (pid
, 0) != 0 && errno
!= EPERM
);
1580 struct timeval delay
; /* how long to wait for file changes. */
1582 delay
.tv_sec
= delay
.tv_usec
= 0;
1585 delay
.tv_sec
= (time_t) sleep_interval
;
1586 delay
.tv_usec
= 1000000 * (sleep_interval
- delay
.tv_sec
);
1593 int file_change
= select (wd
+ 1, &rfd
, NULL
, NULL
, &delay
);
1595 if (file_change
== 0)
1597 else if (file_change
== -1)
1598 die (EXIT_FAILURE
, errno
, _("error monitoring inotify event"));
1601 if (len
<= evbuf_off
)
1603 len
= safe_read (wd
, evbuf
, evlen
);
1606 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1608 if ((len
== 0 || (len
== SAFE_READ_ERROR
&& errno
== EINVAL
))
1613 evbuf
= xrealloc (evbuf
, evlen
);
1617 if (len
== 0 || len
== SAFE_READ_ERROR
)
1618 die (EXIT_FAILURE
, errno
, _("error reading inotify event"));
1621 void_ev
= evbuf
+ evbuf_off
;
1623 evbuf_off
+= sizeof (*ev
) + ev
->len
;
1625 if (ev
->len
) /* event on ev->name in watched directory. */
1628 for (j
= 0; j
< n_files
; j
++)
1630 /* With N=hundreds of frequently-changing files, this O(N^2)
1631 process might be a problem. FIXME: use a hash table? */
1632 if (f
[j
].parent_wd
== ev
->wd
1633 && STREQ (ev
->name
, f
[j
].name
+ f
[j
].basename_start
))
1637 /* It is not a watched file. */
1644 bool deleting
= !! (ev
->mask
& IN_DELETE
);
1648 /* Adding the same inode again will look up any existing wd. */
1649 new_wd
= inotify_add_watch (wd
, f
[j
].name
, inotify_wd_mask
);
1652 if (! deleting
&& new_wd
< 0)
1654 if (errno
== ENOSPC
|| errno
== ENOMEM
)
1656 error (0, 0, _("inotify resources exhausted"));
1657 hash_free (wd_to_name
);
1659 return true; /* revert to polling. */
1663 /* Can get ENOENT for a dangling symlink for example. */
1664 error (0, errno
, _("cannot watch %s"), quoteaf (f
[j
].name
));
1666 /* We'll continue below after removing the existing watch. */
1669 /* This will be false if only attributes of file change. */
1671 new_watch
= (! deleting
) && (fspec
->wd
< 0 || new_wd
!= fspec
->wd
);
1677 inotify_rm_watch (wd
, fspec
->wd
);
1678 hash_delete (wd_to_name
, fspec
);
1686 /* If the file was moved then inotify will use the source file wd
1687 for the destination file. Make sure the key is not present in
1689 struct File_spec
*prev
= hash_delete (wd_to_name
, fspec
);
1690 if (prev
&& prev
!= fspec
)
1692 if (follow_mode
== Follow_name
)
1693 recheck (prev
, false);
1695 close_fd (prev
->fd
, pretty_name (prev
));
1698 if (hash_insert (wd_to_name
, fspec
) == NULL
)
1702 if (follow_mode
== Follow_name
)
1703 recheck (fspec
, false);
1707 struct File_spec key
;
1709 fspec
= hash_lookup (wd_to_name
, &key
);
1715 if (ev
->mask
& (IN_ATTRIB
| IN_DELETE
| IN_DELETE_SELF
| IN_MOVE_SELF
))
1717 /* Note for IN_MOVE_SELF (the file we're watching has
1718 been clobbered via a rename) we leave the watch
1719 in place since it may still be part of the set
1720 of watched names. */
1721 if (ev
->mask
& IN_DELETE_SELF
)
1723 inotify_rm_watch (wd
, fspec
->wd
);
1724 hash_delete (wd_to_name
, fspec
);
1727 /* Note we get IN_ATTRIB for unlink() as st_nlink decrements.
1728 The usual path is a close() done in recheck() triggers
1729 an IN_DELETE_SELF event as the inode is removed.
1730 However sometimes open() will succeed as even though
1731 st_nlink is decremented, the dentry (cache) is not updated.
1732 Thus we depend on the IN_DELETE event on the directory
1733 to trigger processing for the removed file. */
1735 recheck (fspec
, false);
1739 check_fspec (fspec
, &prev_fspec
);
1744 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1745 Return true if successful. */
1748 tail_bytes (const char *pretty_filename
, int fd
, uintmax_t n_bytes
,
1749 uintmax_t *read_pos
)
1753 if (fstat (fd
, &stats
))
1755 error (0, errno
, _("cannot fstat %s"), quoteaf (pretty_filename
));
1761 if ( ! presume_input_pipe
1762 && S_ISREG (stats
.st_mode
) && n_bytes
<= OFF_T_MAX
)
1764 xlseek (fd
, n_bytes
, SEEK_CUR
, pretty_filename
);
1765 *read_pos
+= n_bytes
;
1769 int t
= start_bytes (pretty_filename
, fd
, n_bytes
, read_pos
);
1773 n_bytes
= COPY_TO_EOF
;
1777 off_t end_pos
= ((! presume_input_pipe
&& usable_st_size (&stats
)
1778 && n_bytes
<= OFF_T_MAX
)
1779 ? stats
.st_size
: -1);
1780 if (end_pos
<= ST_BLKSIZE (stats
))
1781 return pipe_bytes (pretty_filename
, fd
, n_bytes
, read_pos
);
1782 off_t current_pos
= xlseek (fd
, 0, SEEK_CUR
, pretty_filename
);
1783 if (current_pos
< end_pos
)
1785 off_t bytes_remaining
= end_pos
- current_pos
;
1787 if (n_bytes
< bytes_remaining
)
1789 current_pos
= end_pos
- n_bytes
;
1790 xlseek (fd
, current_pos
, SEEK_SET
, pretty_filename
);
1793 *read_pos
= current_pos
;
1796 *read_pos
+= dump_remainder (pretty_filename
, fd
, n_bytes
);
1800 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1801 Return true if successful. */
1804 tail_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
1805 uintmax_t *read_pos
)
1809 if (fstat (fd
, &stats
))
1811 error (0, errno
, _("cannot fstat %s"), quoteaf (pretty_filename
));
1817 int t
= start_lines (pretty_filename
, fd
, n_lines
, read_pos
);
1820 *read_pos
+= dump_remainder (pretty_filename
, fd
, COPY_TO_EOF
);
1824 off_t start_pos
= -1;
1827 /* Use file_lines only if FD refers to a regular file for
1828 which lseek (... SEEK_END) works. */
1829 if ( ! presume_input_pipe
1830 && S_ISREG (stats
.st_mode
)
1831 && (start_pos
= lseek (fd
, 0, SEEK_CUR
)) != -1
1832 && start_pos
< (end_pos
= lseek (fd
, 0, SEEK_END
)))
1834 *read_pos
= end_pos
;
1836 && ! file_lines (pretty_filename
, fd
, n_lines
,
1837 start_pos
, end_pos
, read_pos
))
1842 /* Under very unlikely circumstances, it is possible to reach
1843 this point after positioning the file pointer to end of file
1844 via the 'lseek (...SEEK_END)' above. In that case, reposition
1845 the file pointer back to start_pos before calling pipe_lines. */
1846 if (start_pos
!= -1)
1847 xlseek (fd
, start_pos
, SEEK_SET
, pretty_filename
);
1849 return pipe_lines (pretty_filename
, fd
, n_lines
, read_pos
);
1855 /* Display the last N_UNITS units of file FILENAME, open for reading
1856 via FD. Set *READ_POS to the position of the input stream pointer.
1857 *READ_POS is usually the number of bytes read and corresponds to an
1858 offset from the beginning of a file. However, it may be larger than
1859 OFF_T_MAX (as for an input pipe), and may also be larger than the
1860 number of bytes read (when an input pointer is initially not at
1861 beginning of file), and may be far greater than the number of bytes
1862 actually read for an input file that is seekable.
1863 Return true if successful. */
1866 tail (const char *filename
, int fd
, uintmax_t n_units
,
1867 uintmax_t *read_pos
)
1871 return tail_lines (filename
, fd
, n_units
, read_pos
);
1873 return tail_bytes (filename
, fd
, n_units
, read_pos
);
1876 /* Display the last N_UNITS units of the file described by F.
1877 Return true if successful. */
1880 tail_file (struct File_spec
*f
, uintmax_t n_units
)
1885 bool is_stdin
= (STREQ (f
->name
, "-"));
1889 have_read_stdin
= true;
1891 if (O_BINARY
&& ! isatty (STDIN_FILENO
))
1892 xfreopen (NULL
, "rb", stdin
);
1895 fd
= open (f
->name
, O_RDONLY
| O_BINARY
);
1897 f
->tailable
= !(reopen_inaccessible_files
&& fd
== -1);
1905 f
->ignore
= ! reopen_inaccessible_files
;
1909 error (0, errno
, _("cannot open %s for reading"),
1910 quoteaf (pretty_name (f
)));
1918 write_header (pretty_name (f
));
1919 ok
= tail (pretty_name (f
), fd
, n_units
, &read_pos
);
1925 /* Before the tail function provided 'read_pos', there was
1926 a race condition described in the URL below. This sleep
1927 call made the window big enough to exercise the problem. */
1931 if (fstat (fd
, &stats
) < 0)
1935 error (0, errno
, _("error reading %s"),
1936 quoteaf (pretty_name (f
)));
1938 else if (!IS_TAILABLE_FILE_TYPE (stats
.st_mode
))
1942 f
->tailable
= false;
1943 f
->ignore
= ! (reopen_inaccessible_files
1944 && follow_mode
== Follow_name
);
1945 error (0, 0, _("%s: cannot follow end of this type of file%s"),
1946 quotef (pretty_name (f
)),
1947 f
->ignore
? _("; giving up on this name") : "");
1952 close_fd (fd
, pretty_name (f
));
1957 /* Note: we must use read_pos here, not stats.st_size,
1958 to avoid a race condition described by Ken Raeburn:
1959 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1960 record_open_fd (f
, fd
, read_pos
, &stats
, (is_stdin
? -1 : 1));
1961 f
->remote
= fremote (fd
, pretty_name (f
));
1966 if (!is_stdin
&& close (fd
))
1968 error (0, errno
, _("error reading %s"),
1969 quoteaf (pretty_name (f
)));
1978 /* If obsolete usage is allowed, and the command line arguments are of
1979 the obsolete form and the option string is well-formed, set
1980 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1981 return true. If the command line arguments are obviously incorrect
1982 (e.g., because obsolete usage is not allowed and the arguments are
1983 incorrect for non-obsolete usage), report an error and exit.
1984 Otherwise, return false and don't modify any parameter or global
1988 parse_obsolete_option (int argc
, char * const *argv
, uintmax_t *n_units
)
1991 const char *n_string
;
1992 const char *n_string_end
;
1993 int default_count
= DEFAULT_N_LINES
;
1995 bool t_count_lines
= true;
1996 bool t_forever
= false;
1998 /* With the obsolete form, there is one option string and at most
1999 one file argument. Watch out for "-" and "--", though. */
2001 || (argc
== 3 && ! (argv
[2][0] == '-' && argv
[2][1]))
2002 || (3 <= argc
&& argc
<= 4 && STREQ (argv
[2], "--"))))
2005 int posix_ver
= posix2_version ();
2006 bool obsolete_usage
= posix_ver
< 200112;
2007 bool traditional_usage
= obsolete_usage
|| 200809 <= posix_ver
;
2016 /* Leading "+" is a file name in the standard form. */
2017 if (!traditional_usage
)
2020 t_from_start
= true;
2024 /* In the non-obsolete form, "-" is standard input and "-c"
2025 requires an option-argument. The obsolete multidigit options
2026 are supported as a GNU extension even when conforming to
2027 POSIX 1003.1-2001 or later, so don't complain about them. */
2028 if (!obsolete_usage
&& !p
[p
[0] == 'c'])
2031 t_from_start
= false;
2036 while (ISDIGIT (*p
))
2042 case 'b': default_count
*= 512; /* Fall through. */
2043 case 'c': t_count_lines
= false; /* Fall through. */
2044 case 'l': p
++; break;
2056 if (n_string
== n_string_end
)
2057 *n_units
= default_count
;
2058 else if ((xstrtoumax (n_string
, NULL
, 10, n_units
, "b")
2059 & ~LONGINT_INVALID_SUFFIX_CHAR
)
2062 die (EXIT_FAILURE
, errno
, "%s: %s", _("invalid number"),
2067 from_start
= t_from_start
;
2068 count_lines
= t_count_lines
;
2069 forever
= t_forever
;
2075 parse_options (int argc
, char **argv
,
2076 uintmax_t *n_units
, enum header_mode
*header_mode
,
2077 double *sleep_interval
)
2081 while ((c
= getopt_long (argc
, argv
, "c:n:fFqs:vz0123456789",
2082 long_options
, NULL
))
2089 follow_mode
= Follow_name
;
2090 reopen_inaccessible_files
= true;
2095 count_lines
= (c
== 'n');
2098 else if (*optarg
== '-')
2101 *n_units
= xdectoumax (optarg
, 0, UINTMAX_MAX
, "bkKmMGTPEZY0",
2103 ? _("invalid number of lines")
2104 : _("invalid number of bytes"), 0);
2108 case LONG_FOLLOW_OPTION
:
2111 follow_mode
= DEFAULT_FOLLOW_MODE
;
2113 follow_mode
= XARGMATCH ("--follow", optarg
,
2114 follow_mode_string
, follow_mode_map
);
2118 reopen_inaccessible_files
= true;
2121 case MAX_UNCHANGED_STATS_OPTION
:
2122 /* --max-unchanged-stats=N */
2123 max_n_unchanged_stats_between_opens
=
2124 xdectoumax (optarg
, 0, UINTMAX_MAX
, "",
2125 _("invalid maximum number of unchanged stats between opens"), 0);
2128 case DISABLE_INOTIFY_OPTION
:
2129 disable_inotify
= true;
2133 pid
= xdectoumax (optarg
, 0, PID_T_MAX
, "", _("invalid PID"), 0);
2136 case PRESUME_INPUT_PIPE_OPTION
:
2137 presume_input_pipe
= true;
2141 *header_mode
= never
;
2147 if (! (xstrtod (optarg
, NULL
, &s
, c_strtod
) && 0 <= s
))
2148 die (EXIT_FAILURE
, 0,
2149 _("invalid number of seconds: %s"), quote (optarg
));
2150 *sleep_interval
= s
;
2155 *header_mode
= always
;
2162 case_GETOPT_HELP_CHAR
;
2164 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
2166 case '0': case '1': case '2': case '3': case '4':
2167 case '5': case '6': case '7': case '8': case '9':
2168 die (EXIT_FAILURE
, 0, _("option used in invalid context -- %c"), c
);
2171 usage (EXIT_FAILURE
);
2175 if (reopen_inaccessible_files
)
2179 reopen_inaccessible_files
= false;
2180 error (0, 0, _("warning: --retry ignored; --retry is useful"
2181 " only when following"));
2183 else if (follow_mode
== Follow_descriptor
)
2184 error (0, 0, _("warning: --retry only effective for the initial open"));
2187 if (pid
&& !forever
)
2189 _("warning: PID ignored; --pid=PID is useful only when following"));
2190 else if (pid
&& kill (pid
, 0) != 0 && errno
== ENOSYS
)
2192 error (0, 0, _("warning: --pid=PID is not supported on this system"));
2197 /* Mark as '.ignore'd each member of F that corresponds to a
2198 pipe or fifo, and return the number of non-ignored members. */
2200 ignore_fifo_and_pipe (struct File_spec
*f
, size_t n_files
)
2202 /* When there is no FILE operand and stdin is a pipe or FIFO
2203 POSIX requires that tail ignore the -f option.
2204 Since we allow multiple FILE operands, we extend that to say: with -f,
2205 ignore any "-" operand that corresponds to a pipe or FIFO. */
2206 size_t n_viable
= 0;
2209 for (i
= 0; i
< n_files
; i
++)
2211 bool is_a_fifo_or_pipe
=
2212 (STREQ (f
[i
].name
, "-")
2215 && (S_ISFIFO (f
[i
].mode
)
2216 || (HAVE_FIFO_PIPES
!= 1 && isapipe (f
[i
].fd
))));
2217 if (is_a_fifo_or_pipe
)
2230 main (int argc
, char **argv
)
2232 enum header_mode header_mode
= multiple_files
;
2234 /* If from_start, the number of items to skip before printing; otherwise,
2235 the number of items at the end of the file to print. Although the type
2236 is signed, the value is never negative. */
2237 uintmax_t n_units
= DEFAULT_N_LINES
;
2240 struct File_spec
*F
;
2242 bool obsolete_option
;
2244 /* The number of seconds to sleep between iterations.
2245 During one iteration, every file name or descriptor is checked to
2246 see if it has changed. */
2247 double sleep_interval
= 1.0;
2249 initialize_main (&argc
, &argv
);
2250 set_program_name (argv
[0]);
2251 setlocale (LC_ALL
, "");
2252 bindtextdomain (PACKAGE
, LOCALEDIR
);
2253 textdomain (PACKAGE
);
2255 atexit (close_stdout
);
2257 have_read_stdin
= false;
2260 forever
= from_start
= print_headers
= false;
2262 obsolete_option
= parse_obsolete_option (argc
, argv
, &n_units
);
2263 argc
-= obsolete_option
;
2264 argv
+= obsolete_option
;
2265 parse_options (argc
, argv
, &n_units
, &header_mode
, &sleep_interval
);
2267 /* To start printing with item N_UNITS from the start of the file, skip
2268 N_UNITS - 1 items. 'tail -n +0' is actually meaningless, but for Unix
2269 compatibility it's treated the same as 'tail -n +1'. */
2276 IF_LINT (assert (0 <= argc
));
2280 n_files
= argc
- optind
;
2281 file
= argv
+ optind
;
2285 static char *dummy_stdin
= (char *) "-";
2287 file
= &dummy_stdin
;
2291 bool found_hyphen
= false;
2293 for (i
= 0; i
< n_files
; i
++)
2294 if (STREQ (file
[i
], "-"))
2295 found_hyphen
= true;
2297 /* When following by name, there must be a name. */
2298 if (found_hyphen
&& follow_mode
== Follow_name
)
2299 die (EXIT_FAILURE
, 0, _("cannot follow %s by name"), quoteaf ("-"));
2301 /* When following forever, warn if any file is '-'.
2302 This is only a warning, since tail's output (before a failing seek,
2303 and that from any non-stdin files) might still be useful. */
2304 if (forever
&& found_hyphen
&& isatty (STDIN_FILENO
))
2305 error (0, 0, _("warning: following standard input"
2306 " indefinitely is ineffective"));
2309 /* Don't read anything if we'll never output anything. */
2310 if (! n_units
&& ! forever
&& ! from_start
)
2311 return EXIT_SUCCESS
;
2313 F
= xnmalloc (n_files
, sizeof *F
);
2314 for (i
= 0; i
< n_files
; i
++)
2315 F
[i
].name
= file
[i
];
2317 if (header_mode
== always
2318 || (header_mode
== multiple_files
&& n_files
> 1))
2319 print_headers
= true;
2321 if (O_BINARY
&& ! isatty (STDOUT_FILENO
))
2322 xfreopen (NULL
, "wb", stdout
);
2324 for (i
= 0; i
< n_files
; i
++)
2325 ok
&= tail_file (&F
[i
], n_units
);
2327 if (forever
&& ignore_fifo_and_pipe (F
, n_files
))
2330 /* tailable_stdin() checks if the user specifies stdin via "-",
2331 or implicitly by providing no arguments. If so, we won't use inotify.
2332 Technically, on systems with a working /dev/stdin, we *could*,
2333 but would it be worth it? Verifying that it's a real device
2334 and hooked up to stdin is not trivial, while reverting to
2335 non-inotify-based tail_forever is easy and portable.
2337 any_remote_file() checks if the user has specified any
2338 files that reside on remote file systems. inotify is not used
2339 in this case because it would miss any updates to the file
2340 that were not initiated from the local system.
2342 any_non_remote_file() checks if the user has specified any
2343 files that don't reside on remote file systems. inotify is not used
2344 if there are no open files, as we can't determine if those file
2345 will be on a remote file system.
2347 any_symlinks() checks if the user has specified any symbolic links.
2348 inotify is not used in this case because it returns updated _targets_
2349 which would not match the specified names. If we tried to always
2350 use the target names, then we would miss changes to the symlink itself.
2352 ok is false when one of the files specified could not be opened for
2353 reading. In this case and when following by descriptor,
2354 tail_forever_inotify() cannot be used (in its current implementation).
2356 FIXME: inotify doesn't give any notification when a new
2357 (remote) file or directory is mounted on top a watched file.
2358 When follow_mode == Follow_name we would ideally like to detect that.
2359 Note if there is a change to the original file then we'll
2360 recheck it and follow the new file, or ignore it if the
2361 file has changed to being remote.
2363 FIXME: when using inotify, and a directory for a watched file
2364 is recreated, then we don't recheck any new file when
2365 follow_mode == Follow_name.
2367 FIXME-maybe: inotify has a watch descriptor per inode, and hence with
2368 our current hash implementation will only --follow data for one
2369 of the names when multiple hardlinked files are specified, or
2370 for one name when a name is specified multiple times. */
2371 if (!disable_inotify
&& (tailable_stdin (F
, n_files
)
2372 || any_remote_file (F
, n_files
)
2373 || ! any_non_remote_file (F
, n_files
)
2374 || any_symlinks (F
, n_files
)
2375 || (!ok
&& follow_mode
== Follow_descriptor
)))
2376 disable_inotify
= true;
2378 if (!disable_inotify
)
2380 int wd
= inotify_init ();
2383 /* Flush any output from tail_file, now, since
2384 tail_forever_inotify flushes only after writing,
2385 not before reading. */
2386 if (fflush (stdout
) != 0)
2387 die (EXIT_FAILURE
, errno
, _("write error"));
2389 if (! tail_forever_inotify (wd
, F
, n_files
, sleep_interval
))
2390 return EXIT_FAILURE
;
2392 error (0, errno
, _("inotify cannot be used, reverting to polling"));
2394 /* Free resources as this process can be long lived,
2395 and we may have exhausted system resources above. */
2397 for (i
= 0; i
< n_files
; i
++)
2399 /* It's OK to remove the same watch multiple times,
2400 ignoring the EINVAL from redundant calls. */
2402 inotify_rm_watch (wd
, F
[i
].wd
);
2403 if (F
[i
].parent_wd
!= -1)
2404 inotify_rm_watch (wd
, F
[i
].parent_wd
);
2408 disable_inotify
= true;
2409 tail_forever (F
, n_files
, sleep_interval
);
2414 if (have_read_stdin
&& close (STDIN_FILENO
) < 0)
2415 die (EXIT_FAILURE
, errno
, "-");
2416 return ok
? EXIT_SUCCESS
: EXIT_FAILURE
;