1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989-2015 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>
42 #include "safe-read.h"
43 #include "stat-size.h"
44 #include "stat-time.h"
46 #include "xnanosleep.h"
47 #include "xdectoint.h"
53 # include <sys/inotify.h>
54 /* 'select' is used by tail_forever_inotify. */
55 # include <sys/select.h>
57 /* inotify needs to know if a file is local. */
59 # include "fs-is-local.h"
60 # if HAVE_SYS_STATFS_H
61 # include <sys/statfs.h>
67 /* The official name of this program (e.g., no 'g' prefix). */
68 #define PROGRAM_NAME "tail"
71 proper_name ("Paul Rubin"), \
72 proper_name ("David MacKenzie"), \
73 proper_name ("Ian Lance Taylor"), \
74 proper_name ("Jim Meyering")
76 /* Number of items to tail. */
77 #define DEFAULT_N_LINES 10
79 /* Special values for dump_remainder's N_BYTES parameter. */
80 #define COPY_TO_EOF UINTMAX_MAX
81 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
83 /* FIXME: make Follow_name the default? */
84 #define DEFAULT_FOLLOW_MODE Follow_descriptor
88 /* Follow the name of each file: if the file is renamed, try to reopen
89 that name and track the end of the new file if/when it's recreated.
90 This is useful for tracking logs that are occasionally rotated. */
93 /* Follow each descriptor obtained upon opening a file.
94 That means we'll continue to follow the end of a file even after
95 it has been renamed or unlinked. */
99 /* The types of files for which tail works. */
100 #define IS_TAILABLE_FILE_TYPE(Mode) \
101 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
103 static char const *const follow_mode_string
[] =
105 "descriptor", "name", NULL
108 static enum Follow_mode
const follow_mode_map
[] =
110 Follow_descriptor
, Follow_name
,
115 /* The actual file name, or "-" for stdin. */
118 /* Attributes of the file the last time we checked. */
120 struct timespec mtime
;
125 /* The specified name initially referred to a directory or some other
126 type for which tail isn't meaningful. Unlike for a permission problem
127 (tailable, below) once this is set, the name is not checked ever again. */
130 /* See the description of fremote. */
133 /* A file is tailable if it exists, is readable, and is of type
134 IS_TAILABLE_FILE_TYPE. */
137 /* File descriptor on which the file is open; -1 if it's not open. */
140 /* The value of errno seen last time we checked this file. */
143 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
147 /* The watch descriptor used by inotify. */
150 /* The parent directory watch descriptor. It is used only
151 * when Follow_name is used. */
154 /* Offset in NAME of the basename part. */
155 size_t basename_start
;
158 /* See description of DEFAULT_MAX_N_... below. */
159 uintmax_t n_unchanged_stats
;
162 /* Keep trying to open a file even if it is inaccessible when tail starts
163 or if it becomes inaccessible later -- useful only with -f. */
164 static bool reopen_inaccessible_files
;
166 /* If true, interpret the numeric argument as the number of lines.
167 Otherwise, interpret it as the number of bytes. */
168 static bool count_lines
;
170 /* Whether we follow the name of each file or the file descriptor
171 that is initially associated with each name. */
172 static enum Follow_mode follow_mode
= Follow_descriptor
;
174 /* If true, read from the ends of all specified files until killed. */
177 /* If true, count from start of file instead of end. */
178 static bool from_start
;
180 /* If true, print filename headers. */
181 static bool print_headers
;
183 /* When to print the filename banners. */
186 multiple_files
, always
, never
189 /* When tailing a file by name, if there have been this many consecutive
190 iterations for which the file has not changed, then open/fstat
191 the file to determine if that file name is still associated with the
192 same device/inode-number pair as before. This option is meaningful only
193 when following by name. --max-unchanged-stats=N */
194 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
195 static uintmax_t max_n_unchanged_stats_between_opens
=
196 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
;
198 /* The process ID of the process (presumably on the current host)
199 that is writing to all followed files. */
202 /* True if we have ever read standard input. */
203 static bool have_read_stdin
;
205 /* If nonzero, skip the is-regular-file test used to determine whether
206 to use the lseek optimization. Instead, use the more general (and
207 more expensive) code unconditionally. Intended solely for testing. */
208 static bool presume_input_pipe
;
210 /* If nonzero then don't use inotify even if available. */
211 static bool disable_inotify
;
213 /* For long options that have no equivalent short option, use a
214 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
217 RETRY_OPTION
= CHAR_MAX
+ 1,
218 MAX_UNCHANGED_STATS_OPTION
,
220 PRESUME_INPUT_PIPE_OPTION
,
222 DISABLE_INOTIFY_OPTION
225 static struct option
const long_options
[] =
227 {"bytes", required_argument
, NULL
, 'c'},
228 {"follow", optional_argument
, NULL
, LONG_FOLLOW_OPTION
},
229 {"lines", required_argument
, NULL
, 'n'},
230 {"max-unchanged-stats", required_argument
, NULL
, MAX_UNCHANGED_STATS_OPTION
},
231 {"-disable-inotify", no_argument
, NULL
,
232 DISABLE_INOTIFY_OPTION
}, /* do not document */
233 {"pid", required_argument
, NULL
, PID_OPTION
},
234 {"-presume-input-pipe", no_argument
, NULL
,
235 PRESUME_INPUT_PIPE_OPTION
}, /* do not document */
236 {"quiet", no_argument
, NULL
, 'q'},
237 {"retry", no_argument
, NULL
, RETRY_OPTION
},
238 {"silent", no_argument
, NULL
, 'q'},
239 {"sleep-interval", required_argument
, NULL
, 's'},
240 {"verbose", no_argument
, NULL
, 'v'},
241 {GETOPT_HELP_OPTION_DECL
},
242 {GETOPT_VERSION_OPTION_DECL
},
249 if (status
!= EXIT_SUCCESS
)
254 Usage: %s [OPTION]... [FILE]...\n\
258 Print the last %d lines of each FILE to standard output.\n\
259 With more than one FILE, precede each with a header giving the file name.\n\
260 "), DEFAULT_N_LINES
);
263 emit_mandatory_arg_note ();
266 -c, --bytes=K output the last K bytes; or use -c +K to output\n\
267 bytes starting with the Kth of each file\n\
270 -f, --follow[={name|descriptor}]\n\
271 output appended data as the file grows;\n\
272 an absent option argument means 'descriptor'\n\
273 -F same as --follow=name --retry\n\
276 -n, --lines=K output the last K lines, instead of the last %d;\n\
277 or use -n +K to output starting with the Kth\n\
278 --max-unchanged-stats=N\n\
279 with --follow=name, reopen a FILE which has not\n\
280 changed size after N (default %d) iterations\n\
281 to see if it has been unlinked or renamed\n\
282 (this is the usual case of rotated log files);\n\
283 with inotify, this option is rarely useful\n\
286 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
289 --pid=PID with -f, terminate after process ID, PID dies\n\
290 -q, --quiet, --silent never output headers giving file names\n\
291 --retry keep trying to open a file if it is inaccessible\n\
294 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
295 (default 1.0) between iterations;\n\
296 with inotify and --pid=P, check process P at\n\
297 least once every N seconds\n\
298 -v, --verbose always output headers giving file names\n\
300 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
301 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
304 If the first character of K (the number of bytes or lines) is a '+',\n\
305 print beginning with the Kth item from the start of each file, otherwise,\n\
306 print the last K items in the file. K may have a multiplier suffix:\n\
307 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
308 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
312 With --follow (-f), tail defaults to following the file descriptor, which\n\
313 means that even if a tail'ed file is renamed, tail will continue to track\n\
314 its end. This default behavior is not desirable when you really want to\n\
315 track the actual name of the file, not the file descriptor (e.g., log\n\
316 rotation). Use --follow=name in that case. That causes tail to track the\n\
317 named file in a way that accommodates renaming, removal and creation.\n\
319 emit_ancillary_info (PROGRAM_NAME
);
325 valid_file_spec (struct File_spec
const *f
)
327 /* Exactly one of the following subexpressions must be true. */
328 return ((f
->fd
== -1) ^ (f
->errnum
== 0));
332 pretty_name (struct File_spec
const *f
)
334 return (STREQ (f
->name
, "-") ? _("standard input") : f
->name
);
337 /* Record a file F with descriptor FD, size SIZE, status ST, and
338 blocking status BLOCKING. */
341 record_open_fd (struct File_spec
*f
, int fd
,
342 off_t size
, struct stat
const *st
,
347 f
->mtime
= get_stat_mtime (st
);
350 f
->mode
= st
->st_mode
;
351 f
->blocking
= blocking
;
352 f
->n_unchanged_stats
= 0;
356 /* Close the file with descriptor FD and name FILENAME. */
359 close_fd (int fd
, const char *filename
)
361 if (fd
!= -1 && fd
!= STDIN_FILENO
&& close (fd
))
363 error (0, errno
, _("closing %s (fd=%d)"), filename
, fd
);
368 write_header (const char *pretty_filename
)
370 static bool first_file
= true;
372 printf ("%s==> %s <==\n", (first_file
? "" : "\n"), pretty_filename
);
376 /* Write N_BYTES from BUFFER to stdout.
377 Exit immediately on error with a single diagnostic. */
380 xwrite_stdout (char const *buffer
, size_t n_bytes
)
382 if (n_bytes
> 0 && fwrite (buffer
, 1, n_bytes
, stdout
) < n_bytes
)
384 clearerr (stdout
); /* To avoid redundant close_stdout diagnostic. */
385 error (EXIT_FAILURE
, errno
, _("error writing %s"),
386 quote ("standard output"));
390 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
391 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
392 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
393 Return the number of bytes read from the file. */
396 dump_remainder (const char *pretty_filename
, int fd
, uintmax_t n_bytes
)
399 uintmax_t n_remaining
= n_bytes
;
405 size_t n
= MIN (n_remaining
, BUFSIZ
);
406 size_t bytes_read
= safe_read (fd
, buffer
, n
);
407 if (bytes_read
== SAFE_READ_ERROR
)
410 error (EXIT_FAILURE
, errno
, _("error reading %s"),
411 quote (pretty_filename
));
416 xwrite_stdout (buffer
, bytes_read
);
417 n_written
+= bytes_read
;
418 if (n_bytes
!= COPY_TO_EOF
)
420 n_remaining
-= bytes_read
;
421 if (n_remaining
== 0 || n_bytes
== COPY_A_BUFFER
)
429 /* Call lseek with the specified arguments, where file descriptor FD
430 corresponds to the file, FILENAME.
431 Give a diagnostic and exit nonzero if lseek fails.
432 Otherwise, return the resulting offset. */
435 xlseek (int fd
, off_t offset
, int whence
, char const *filename
)
437 off_t new_offset
= lseek (fd
, offset
, whence
);
438 char buf
[INT_BUFSIZE_BOUND (offset
)];
444 s
= offtostr (offset
, buf
);
448 error (0, errno
, _("%s: cannot seek to offset %s"),
452 error (0, errno
, _("%s: cannot seek to relative offset %s"),
456 error (0, errno
, _("%s: cannot seek to end-relative offset %s"),
466 /* Print the last N_LINES lines from the end of file FD.
467 Go backward through the file, reading 'BUFSIZ' bytes at a time (except
468 probably the first), until we hit the start of the file or have
469 read NUMBER newlines.
470 START_POS is the starting position of the read pointer for the file
471 associated with FD (may be nonzero).
472 END_POS is the file offset of EOF (one larger than offset of last byte).
473 Return true if successful. */
476 file_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
477 off_t start_pos
, off_t end_pos
, uintmax_t *read_pos
)
486 /* Set 'bytes_read' to the size of the last, probably partial, buffer;
487 0 < 'bytes_read' <= 'BUFSIZ'. */
488 bytes_read
= (pos
- start_pos
) % BUFSIZ
;
491 /* Make 'pos' a multiple of 'BUFSIZ' (0 if the file is short), so that all
492 reads will be on block boundaries, which might increase efficiency. */
494 xlseek (fd
, pos
, SEEK_SET
, pretty_filename
);
495 bytes_read
= safe_read (fd
, buffer
, bytes_read
);
496 if (bytes_read
== SAFE_READ_ERROR
)
498 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
501 *read_pos
= pos
+ bytes_read
;
503 /* Count the incomplete line on files that don't end with a newline. */
504 if (bytes_read
&& buffer
[bytes_read
- 1] != '\n')
509 /* Scan backward, counting the newlines in this bufferfull. */
511 size_t n
= bytes_read
;
515 nl
= memrchr (buffer
, '\n', n
);
521 /* If this newline isn't the last character in the buffer,
522 output the part that is after it. */
523 if (n
!= bytes_read
- 1)
524 xwrite_stdout (nl
+ 1, bytes_read
- (n
+ 1));
525 *read_pos
+= dump_remainder (pretty_filename
, fd
,
526 end_pos
- (pos
+ bytes_read
));
531 /* Not enough newlines in that bufferfull. */
532 if (pos
== start_pos
)
534 /* Not enough lines in the file; print everything from
535 start_pos to the end. */
536 xlseek (fd
, start_pos
, SEEK_SET
, pretty_filename
);
537 *read_pos
= start_pos
+ dump_remainder (pretty_filename
, fd
,
542 xlseek (fd
, pos
, SEEK_SET
, pretty_filename
);
544 bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
545 if (bytes_read
== SAFE_READ_ERROR
)
547 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
551 *read_pos
= pos
+ bytes_read
;
553 while (bytes_read
> 0);
558 /* Print the last N_LINES lines from the end of the standard input,
559 open for reading as pipe FD.
560 Buffer the text as a linked list of LBUFFERs, adding them as needed.
561 Return true if successful. */
564 pipe_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
572 struct linebuffer
*next
;
574 typedef struct linebuffer LBUFFER
;
575 LBUFFER
*first
, *last
, *tmp
;
576 size_t total_lines
= 0; /* Total number of newlines in all buffers. */
578 size_t n_read
; /* Size in bytes of most recent read */
580 first
= last
= xmalloc (sizeof (LBUFFER
));
581 first
->nbytes
= first
->nlines
= 0;
583 tmp
= xmalloc (sizeof (LBUFFER
));
585 /* Input is always read into a fresh buffer. */
588 n_read
= safe_read (fd
, tmp
->buffer
, BUFSIZ
);
589 if (n_read
== 0 || n_read
== SAFE_READ_ERROR
)
591 tmp
->nbytes
= n_read
;
596 /* Count the number of newlines just read. */
598 char const *buffer_end
= tmp
->buffer
+ n_read
;
599 char const *p
= tmp
->buffer
;
600 while ((p
= memchr (p
, '\n', buffer_end
- p
)))
606 total_lines
+= tmp
->nlines
;
608 /* If there is enough room in the last buffer read, just append the new
609 one to it. This is because when reading from a pipe, 'n_read' can
610 often be very small. */
611 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
613 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
614 last
->nbytes
+= tmp
->nbytes
;
615 last
->nlines
+= tmp
->nlines
;
619 /* If there's not enough room, link the new buffer onto the end of
620 the list, then either free up the oldest buffer for the next
621 read if that would leave enough lines, or else malloc a new one.
622 Some compaction mechanism is possible but probably not
624 last
= last
->next
= tmp
;
625 if (total_lines
- first
->nlines
> n_lines
)
628 total_lines
-= first
->nlines
;
632 tmp
= xmalloc (sizeof (LBUFFER
));
638 if (n_read
== SAFE_READ_ERROR
)
640 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
645 /* If the file is empty, then bail out. */
646 if (last
->nbytes
== 0)
649 /* This prevents a core dump when the pipe contains no newlines. */
653 /* Count the incomplete line on files that don't end with a newline. */
654 if (last
->buffer
[last
->nbytes
- 1] != '\n')
660 /* Run through the list, printing lines. First, skip over unneeded
662 for (tmp
= first
; total_lines
- tmp
->nlines
> n_lines
; tmp
= tmp
->next
)
663 total_lines
-= tmp
->nlines
;
665 /* Find the correct beginning, then print the rest of the file. */
667 char const *beg
= tmp
->buffer
;
668 char const *buffer_end
= tmp
->buffer
+ tmp
->nbytes
;
669 if (total_lines
> n_lines
)
671 /* Skip 'total_lines' - 'n_lines' newlines. We made sure that
672 'total_lines' - 'n_lines' <= 'tmp->nlines'. */
674 for (j
= total_lines
- n_lines
; j
; --j
)
676 beg
= memchr (beg
, '\n', buffer_end
- beg
);
682 xwrite_stdout (beg
, buffer_end
- beg
);
685 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
686 xwrite_stdout (tmp
->buffer
, tmp
->nbytes
);
698 /* Print the last N_BYTES characters from the end of pipe FD.
699 This is a stripped down version of pipe_lines.
700 Return true if successful. */
703 pipe_bytes (const char *pretty_filename
, int fd
, uintmax_t n_bytes
,
710 struct charbuffer
*next
;
712 typedef struct charbuffer CBUFFER
;
713 CBUFFER
*first
, *last
, *tmp
;
714 size_t i
; /* Index into buffers. */
715 size_t total_bytes
= 0; /* Total characters in all buffers. */
719 first
= last
= xmalloc (sizeof (CBUFFER
));
722 tmp
= xmalloc (sizeof (CBUFFER
));
724 /* Input is always read into a fresh buffer. */
727 n_read
= safe_read (fd
, tmp
->buffer
, BUFSIZ
);
728 if (n_read
== 0 || n_read
== SAFE_READ_ERROR
)
731 tmp
->nbytes
= n_read
;
734 total_bytes
+= tmp
->nbytes
;
735 /* If there is enough room in the last buffer read, just append the new
736 one to it. This is because when reading from a pipe, 'nbytes' can
737 often be very small. */
738 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
740 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
741 last
->nbytes
+= tmp
->nbytes
;
745 /* If there's not enough room, link the new buffer onto the end of
746 the list, then either free up the oldest buffer for the next
747 read if that would leave enough characters, or else malloc a new
748 one. Some compaction mechanism is possible but probably not
750 last
= last
->next
= tmp
;
751 if (total_bytes
- first
->nbytes
> n_bytes
)
754 total_bytes
-= first
->nbytes
;
759 tmp
= xmalloc (sizeof (CBUFFER
));
766 if (n_read
== SAFE_READ_ERROR
)
768 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
773 /* Run through the list, printing characters. First, skip over unneeded
775 for (tmp
= first
; total_bytes
- tmp
->nbytes
> n_bytes
; tmp
= tmp
->next
)
776 total_bytes
-= tmp
->nbytes
;
778 /* Find the correct beginning, then print the rest of the file.
779 We made sure that 'total_bytes' - 'n_bytes' <= 'tmp->nbytes'. */
780 if (total_bytes
> n_bytes
)
781 i
= total_bytes
- n_bytes
;
784 xwrite_stdout (&tmp
->buffer
[i
], tmp
->nbytes
- i
);
786 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
787 xwrite_stdout (tmp
->buffer
, tmp
->nbytes
);
799 /* Skip N_BYTES characters from the start of pipe FD, and print
800 any extra characters that were read beyond that.
801 Return 1 on error, 0 if ok, -1 if EOF. */
804 start_bytes (const char *pretty_filename
, int fd
, uintmax_t n_bytes
,
811 size_t bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
814 if (bytes_read
== SAFE_READ_ERROR
)
816 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
819 *read_pos
+= bytes_read
;
820 if (bytes_read
<= n_bytes
)
821 n_bytes
-= bytes_read
;
824 size_t n_remaining
= bytes_read
- n_bytes
;
826 xwrite_stdout (&buffer
[n_bytes
], n_remaining
);
834 /* Skip N_LINES lines at the start of file or pipe FD, and print
835 any extra characters that were read beyond that.
836 Return 1 on error, 0 if ok, -1 if EOF. */
839 start_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
848 size_t bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
849 if (bytes_read
== 0) /* EOF */
851 if (bytes_read
== SAFE_READ_ERROR
) /* error */
853 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
857 char *buffer_end
= buffer
+ bytes_read
;
859 *read_pos
+= bytes_read
;
862 while ((p
= memchr (p
, '\n', buffer_end
- p
)))
868 xwrite_stdout (p
, buffer_end
- p
);
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. */
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__
887 int err
= fstatfs (fd
, &buf
);
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. */
893 error (0, errno
, _("cannot determine location of %s. "
894 "reverting to polling"), quote (name
));
898 switch (is_local_fs_type (buf
.f_type
))
904 unsigned long int fs_type
= buf
.f_type
;
905 error (0, 0, _("unrecognized file system type 0x%08lx for %s. "
906 "please report this to %s. reverting to polling"),
907 fs_type
, quote (name
), PACKAGE_BUGREPORT
);
908 /* Treat as "remote", so caller polls. */
915 assert (!"unexpected return value from is_local_fs_type");
923 /* Without inotify support, whether a file is remote is irrelevant.
924 Always return "false" in that case. */
925 # define fremote(fd, name) false
928 /* open/fstat F->name and handle changes. */
930 recheck (struct File_spec
*f
, bool blocking
)
932 struct stat new_stats
;
934 bool is_stdin
= (STREQ (f
->name
, "-"));
935 bool was_tailable
= f
->tailable
;
936 int prev_errnum
= f
->errnum
;
940 : open (f
->name
, O_RDONLY
| (blocking
? 0 : O_NONBLOCK
)));
942 assert (valid_file_spec (f
));
944 /* If the open fails because the file doesn't exist,
945 then mark the file as not tailable. */
946 f
->tailable
= !(reopen_inaccessible_files
&& fd
== -1);
948 if (! disable_inotify
&& ! lstat (f
->name
, &new_stats
)
949 && S_ISLNK (new_stats
.st_mode
))
951 /* Diagnose the edge case where a regular file is changed
952 to a symlink. We avoid inotify with symlinks since
953 it's awkward to match between symlink name and target. */
958 error (0, 0, _("%s has been replaced with a symbolic link. "
959 "giving up on this name"), quote (pretty_name (f
)));
961 else if (fd
== -1 || fstat (fd
, &new_stats
) < 0)
969 /* FIXME-maybe: detect the case in which the file first becomes
970 unreadable (perms), and later becomes readable again and can
971 be seen to be the same file (dev/ino). Otherwise, tail prints
972 the entire contents of the file when it becomes readable. */
973 error (0, f
->errnum
, _("%s has become inaccessible"),
974 quote (pretty_name (f
)));
978 /* say nothing... it's still not tailable */
981 else if (prev_errnum
!= errno
)
983 error (0, errno
, "%s", pretty_name (f
));
986 else if (!IS_TAILABLE_FILE_TYPE (new_stats
.st_mode
))
990 error (0, 0, _("%s has been replaced with an untailable file;\
991 giving up on this name"),
992 quote (pretty_name (f
)));
995 else if (!disable_inotify
&& fremote (fd
, pretty_name (f
)))
999 error (0, 0, _("%s has been replaced with a remote file. "
1000 "giving up on this name"), quote (pretty_name (f
)));
1012 close_fd (fd
, pretty_name (f
));
1013 close_fd (f
->fd
, pretty_name (f
));
1016 else if (prev_errnum
&& prev_errnum
!= ENOENT
)
1019 assert (f
->fd
== -1);
1020 error (0, 0, _("%s has become accessible"), quote (pretty_name (f
)));
1022 else if (f
->ino
!= new_stats
.st_ino
|| f
->dev
!= new_stats
.st_dev
)
1028 _("%s has appeared; following new file"),
1029 quote (pretty_name (f
)));
1033 /* Close the old one. */
1034 close_fd (f
->fd
, pretty_name (f
));
1036 /* File has been replaced (e.g., via log rotation) --
1037 tail the new one. */
1039 _("%s has been replaced; following new file"),
1040 quote (pretty_name (f
)));
1047 /* This happens when one iteration finds the file missing,
1048 then the preceding <dev,inode> pair is reused as the
1049 file is recreated. */
1054 close_fd (fd
, pretty_name (f
));
1058 /* FIXME: When a log is rotated, daemons tend to log to the
1059 old file descriptor until the new file is present and
1060 the daemon is sent a signal. Therefore tail may miss entries
1061 being written to the old file. Perhaps we should keep
1062 the older file open and continue to monitor it until
1063 data is written to a new file. */
1066 /* Start at the beginning of the file. */
1067 record_open_fd (f
, fd
, 0, &new_stats
, (is_stdin
? -1 : blocking
));
1068 xlseek (fd
, 0, SEEK_SET
, pretty_name (f
));
1072 /* Return true if any of the N_FILES files in F are live, i.e., have
1073 open file descriptors, or should be checked again (see --retry).
1074 When following descriptors, checking should only continue when any
1075 of the files is not yet ignored. */
1078 any_live_files (const struct File_spec
*f
, size_t n_files
)
1082 if (reopen_inaccessible_files
&& follow_mode
== Follow_name
)
1083 return true; /* continue following for -F option */
1085 for (i
= 0; i
< n_files
; i
++)
1093 if (reopen_inaccessible_files
&& follow_mode
== Follow_descriptor
)
1102 /* Tail N_FILES files forever, or until killed.
1103 The pertinent information for each file is stored in an entry of F.
1104 Loop over each of them, doing an fstat to see if they have changed size,
1105 and an occasional open/fstat to see if any dev/ino pair has changed.
1106 If none of them have changed size in one iteration, sleep for a
1107 while and try again. Continue until the user interrupts us. */
1110 tail_forever (struct File_spec
*f
, size_t n_files
, double sleep_interval
)
1112 /* Use blocking I/O as an optimization, when it's easy. */
1113 bool blocking
= (pid
== 0 && follow_mode
== Follow_descriptor
1114 && n_files
== 1 && ! S_ISREG (f
[0].mode
));
1116 bool writer_is_dead
= false;
1123 bool any_input
= false;
1125 for (i
= 0; i
< n_files
; i
++)
1131 uintmax_t bytes_read
;
1138 recheck (&f
[i
], blocking
);
1143 name
= pretty_name (&f
[i
]);
1146 if (f
[i
].blocking
!= blocking
)
1148 int old_flags
= fcntl (fd
, F_GETFL
);
1149 int new_flags
= old_flags
| (blocking
? 0 : O_NONBLOCK
);
1151 || (new_flags
!= old_flags
1152 && fcntl (fd
, F_SETFL
, new_flags
) == -1))
1154 /* Don't update f[i].blocking if fcntl fails. */
1155 if (S_ISREG (f
[i
].mode
) && errno
== EPERM
)
1157 /* This happens when using tail -f on a file with
1158 the append-only attribute. */
1161 error (EXIT_FAILURE
, errno
,
1162 _("%s: cannot change nonblocking mode"), name
);
1165 f
[i
].blocking
= blocking
;
1170 if (fstat (fd
, &stats
) != 0)
1173 f
[i
].errnum
= errno
;
1174 error (0, errno
, "%s", name
);
1175 close (fd
); /* ignore failure */
1179 if (f
[i
].mode
== stats
.st_mode
1180 && (! S_ISREG (stats
.st_mode
) || f
[i
].size
== stats
.st_size
)
1181 && timespec_cmp (f
[i
].mtime
, get_stat_mtime (&stats
)) == 0)
1183 if ((max_n_unchanged_stats_between_opens
1184 <= f
[i
].n_unchanged_stats
++)
1185 && follow_mode
== Follow_name
)
1187 recheck (&f
[i
], f
[i
].blocking
);
1188 f
[i
].n_unchanged_stats
= 0;
1193 /* This file has changed. Print out what we can, and
1194 then keep looping. */
1196 f
[i
].mtime
= get_stat_mtime (&stats
);
1197 f
[i
].mode
= stats
.st_mode
;
1200 f
[i
].n_unchanged_stats
= 0;
1202 /* XXX: This is only a heuristic, as the file may have also
1203 been truncated and written to if st_size >= size
1204 (in which case we ignore new data <= size). */
1205 if (S_ISREG (mode
) && stats
.st_size
< f
[i
].size
)
1207 error (0, 0, _("%s: file truncated"), name
);
1208 /* Assume the file was truncated to 0,
1209 and therefore output all "new" data. */
1210 xlseek (fd
, 0, SEEK_SET
, name
);
1217 write_header (name
);
1222 bytes_read
= dump_remainder (name
, fd
,
1224 ? COPY_A_BUFFER
: COPY_TO_EOF
));
1225 any_input
|= (bytes_read
!= 0);
1226 f
[i
].size
+= bytes_read
;
1229 if (! any_live_files (f
, n_files
))
1231 error (0, 0, _("no files remaining"));
1235 if ((!any_input
|| blocking
) && fflush (stdout
) != 0)
1236 error (EXIT_FAILURE
, errno
, _("write error"));
1238 /* If nothing was read, sleep and/or check for dead writers. */
1244 /* Once the writer is dead, read the files once more to
1245 avoid a race condition. */
1246 writer_is_dead
= (pid
!= 0
1247 && kill (pid
, 0) != 0
1248 /* Handle the case in which you cannot send a
1249 signal to the writer, so kill fails and sets
1253 if (!writer_is_dead
&& xnanosleep (sleep_interval
))
1254 error (EXIT_FAILURE
, errno
, _("cannot read realtime clock"));
1262 /* Return true if any of the N_FILES files in F is remote, i.e., has
1263 an open file descriptor and is on a network file system. */
1266 any_remote_file (const struct File_spec
*f
, size_t n_files
)
1270 for (i
= 0; i
< n_files
; i
++)
1271 if (0 <= f
[i
].fd
&& f
[i
].remote
)
1276 /* Return true if any of the N_FILES files in F is a symlink.
1277 Note we don't worry about the edge case where "-" exists,
1278 since that will have the same consequences for inotify,
1279 which is the only context this function is currently used. */
1282 any_symlinks (const struct File_spec
*f
, size_t n_files
)
1287 for (i
= 0; i
< n_files
; i
++)
1288 if (lstat (f
[i
].name
, &st
) == 0 && S_ISLNK (st
.st_mode
))
1293 /* Return true if any of the N_FILES files in F represents
1294 stdin and is tailable. */
1297 tailable_stdin (const struct File_spec
*f
, size_t n_files
)
1301 for (i
= 0; i
< n_files
; i
++)
1302 if (!f
[i
].ignore
&& STREQ (f
[i
].name
, "-"))
1308 wd_hasher (const void *entry
, size_t tabsize
)
1310 const struct File_spec
*spec
= entry
;
1311 return spec
->wd
% tabsize
;
1315 wd_comparator (const void *e1
, const void *e2
)
1317 const struct File_spec
*spec1
= e1
;
1318 const struct File_spec
*spec2
= e2
;
1319 return spec1
->wd
== spec2
->wd
;
1322 /* Output (new) data for FSPEC->fd. */
1324 check_fspec (struct File_spec
*fspec
, int wd
, int *prev_wd
)
1329 if (fspec
->fd
== -1)
1332 name
= pretty_name (fspec
);
1334 if (fstat (fspec
->fd
, &stats
) != 0)
1336 fspec
->errnum
= errno
;
1337 close_fd (fspec
->fd
, name
);
1342 /* XXX: This is only a heuristic, as the file may have also
1343 been truncated and written to if st_size >= size
1344 (in which case we ignore new data <= size).
1345 Though in the inotify case it's more likely we'll get
1346 separate events for truncate() and write(). */
1347 if (S_ISREG (fspec
->mode
) && stats
.st_size
< fspec
->size
)
1349 error (0, 0, _("%s: file truncated"), name
);
1351 xlseek (fspec
->fd
, 0, SEEK_SET
, name
);
1354 else if (S_ISREG (fspec
->mode
) && stats
.st_size
== fspec
->size
1355 && timespec_cmp (fspec
->mtime
, get_stat_mtime (&stats
)) == 0)
1361 write_header (name
);
1365 uintmax_t bytes_read
= dump_remainder (name
, fspec
->fd
, COPY_TO_EOF
);
1366 fspec
->size
+= bytes_read
;
1368 if (fflush (stdout
) != 0)
1369 error (EXIT_FAILURE
, errno
, _("write error"));
1372 /* Attempt to tail N_FILES files forever, or until killed.
1373 Check modifications using the inotify events system.
1374 Return false on error, or true to revert to polling. */
1376 tail_forever_inotify (int wd
, struct File_spec
*f
, size_t n_files
,
1377 double sleep_interval
)
1379 # if TAIL_TEST_SLEEP
1380 /* Delay between open() and inotify_add_watch()
1381 to help trigger different cases. */
1382 xnanosleep (1000000);
1384 unsigned int max_realloc
= 3;
1386 /* Map an inotify watch descriptor to the name of the file it's watching. */
1387 Hash_table
*wd_to_name
;
1389 bool found_watchable_file
= false;
1390 bool tailed_but_unwatchable
= false;
1391 bool found_unwatchable_dir
= false;
1392 bool no_inotify_resources
= false;
1393 bool writer_is_dead
= false;
1397 size_t evbuf_off
= 0;
1400 wd_to_name
= hash_initialize (n_files
, NULL
, wd_hasher
, wd_comparator
, NULL
);
1404 /* The events mask used with inotify on files (not directories). */
1405 uint32_t inotify_wd_mask
= IN_MODIFY
;
1406 /* TODO: Perhaps monitor these events in Follow_descriptor mode also,
1407 to tag reported file names with "deleted", "moved" etc. */
1408 if (follow_mode
== Follow_name
)
1409 inotify_wd_mask
|= (IN_ATTRIB
| IN_DELETE_SELF
| IN_MOVE_SELF
);
1411 /* Add an inotify watch for each watched file. If -F is specified then watch
1412 its parent directory too, in this way when they re-appear we can add them
1413 again to the watch list. */
1415 for (i
= 0; i
< n_files
; i
++)
1419 size_t fnlen
= strlen (f
[i
].name
);
1425 if (follow_mode
== Follow_name
)
1427 size_t dirlen
= dir_len (f
[i
].name
);
1428 char prev
= f
[i
].name
[dirlen
];
1429 f
[i
].basename_start
= last_component (f
[i
].name
) - f
[i
].name
;
1431 f
[i
].name
[dirlen
] = '\0';
1433 /* It's fine to add the same directory more than once.
1434 In that case the same watch descriptor is returned. */
1435 f
[i
].parent_wd
= inotify_add_watch (wd
, dirlen
? f
[i
].name
: ".",
1436 (IN_CREATE
| IN_MOVED_TO
1439 f
[i
].name
[dirlen
] = prev
;
1441 if (f
[i
].parent_wd
< 0)
1443 if (errno
!= ENOSPC
) /* suppress confusing error. */
1444 error (0, errno
, _("cannot watch parent directory of %s"),
1447 error (0, 0, _("inotify resources exhausted"));
1448 found_unwatchable_dir
= true;
1449 /* We revert to polling below. Note invalid uses
1450 of the inotify API will still be diagnosed. */
1455 f
[i
].wd
= inotify_add_watch (wd
, f
[i
].name
, inotify_wd_mask
);
1459 if (f
[i
].fd
!= -1) /* already tailed. */
1460 tailed_but_unwatchable
= true;
1461 if (errno
== ENOSPC
|| errno
== ENOMEM
)
1463 no_inotify_resources
= true;
1464 error (0, 0, _("inotify resources exhausted"));
1467 else if (errno
!= f
[i
].errnum
)
1468 error (0, errno
, _("cannot watch %s"), quote (f
[i
].name
));
1472 if (hash_insert (wd_to_name
, &(f
[i
])) == NULL
)
1475 found_watchable_file
= true;
1479 /* Linux kernel 2.6.24 at least has a bug where eventually, ENOSPC is always
1480 returned by inotify_add_watch. In any case we should revert to polling
1481 when there are no inotify resources. Also a specified directory may not
1482 be currently present or accessible, so revert to polling. Also an already
1483 tailed but unwatchable due rename/unlink race, should also revert. */
1484 if (no_inotify_resources
|| found_unwatchable_dir
1485 || (follow_mode
== Follow_descriptor
&& tailed_but_unwatchable
))
1487 hash_free (wd_to_name
);
1492 if (follow_mode
== Follow_descriptor
&& !found_watchable_file
)
1495 prev_wd
= f
[n_files
- 1].wd
;
1497 /* Check files again. New files or data can be available since last time we
1498 checked and before they are watched by inotify. */
1499 for (i
= 0; i
< n_files
; i
++)
1503 /* check for new files. */
1504 if (follow_mode
== Follow_name
)
1505 recheck (&(f
[i
]), false);
1506 else if (f
[i
].fd
!= -1)
1508 /* If the file was replaced in the small window since we tailed,
1509 then assume the watch is on the wrong item (different to
1510 that we've already produced output for), and so revert to
1511 polling the original descriptor. */
1514 if (stat (f
[i
].name
, &stats
) == 0
1515 && (f
[i
].dev
!= stats
.st_dev
|| f
[i
].ino
!= stats
.st_ino
))
1517 error (0, errno
, _("%s was replaced"),
1518 quote (pretty_name (&(f
[i
]))));
1519 hash_free (wd_to_name
);
1526 /* check for new data. */
1527 check_fspec (&f
[i
], f
[i
].wd
, &prev_wd
);
1531 evlen
+= sizeof (struct inotify_event
) + 1;
1532 evbuf
= xmalloc (evlen
);
1534 /* Wait for inotify events and handle them. Events on directories
1535 ensure that watched files can be re-added when following by name.
1536 This loop blocks on the 'safe_read' call until a new event is notified.
1537 But when --pid=P is specified, tail usually waits via the select. */
1540 struct File_spec
*fspec
;
1541 struct inotify_event
*ev
;
1544 /* When following by name without --retry, and the last file has
1545 been unlinked or renamed-away, diagnose it and return. */
1546 if (follow_mode
== Follow_name
1547 && ! reopen_inaccessible_files
1548 && hash_get_n_entries (wd_to_name
) == 0)
1550 error (0, 0, _("no files remaining"));
1554 /* When watching a PID, ensure that a read from WD will not block
1559 exit (EXIT_SUCCESS
);
1561 writer_is_dead
= (kill (pid
, 0) != 0 && errno
!= EPERM
);
1563 struct timeval delay
; /* how long to wait for file changes. */
1565 delay
.tv_sec
= delay
.tv_usec
= 0;
1568 delay
.tv_sec
= (time_t) sleep_interval
;
1569 delay
.tv_usec
= 1000000 * (sleep_interval
- delay
.tv_sec
);
1576 int file_change
= select (wd
+ 1, &rfd
, NULL
, NULL
, &delay
);
1578 if (file_change
== 0)
1580 else if (file_change
== -1)
1581 error (EXIT_FAILURE
, errno
, _("error monitoring inotify event"));
1584 if (len
<= evbuf_off
)
1586 len
= safe_read (wd
, evbuf
, evlen
);
1589 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1591 if ((len
== 0 || (len
== SAFE_READ_ERROR
&& errno
== EINVAL
))
1596 evbuf
= xrealloc (evbuf
, evlen
);
1600 if (len
== 0 || len
== SAFE_READ_ERROR
)
1601 error (EXIT_FAILURE
, errno
, _("error reading inotify event"));
1604 void_ev
= evbuf
+ evbuf_off
;
1606 evbuf_off
+= sizeof (*ev
) + ev
->len
;
1608 if (ev
->len
) /* event on ev->name in watched directory. */
1611 for (j
= 0; j
< n_files
; j
++)
1613 /* With N=hundreds of frequently-changing files, this O(N^2)
1614 process might be a problem. FIXME: use a hash table? */
1615 if (f
[j
].parent_wd
== ev
->wd
1616 && STREQ (ev
->name
, f
[j
].name
+ f
[j
].basename_start
))
1620 /* It is not a watched file. */
1626 /* Adding the same inode again will look up any existing wd. */
1627 int new_wd
= inotify_add_watch (wd
, f
[j
].name
, inotify_wd_mask
);
1630 if (errno
== ENOSPC
|| errno
== ENOMEM
)
1632 error (0, 0, _("inotify resources exhausted"));
1633 hash_free (wd_to_name
);
1635 return true; /* revert to polling. */
1639 /* Can get ENOENT for a dangling symlink for example. */
1640 error (0, errno
, _("cannot watch %s"), quote (f
[j
].name
));
1642 /* We'll continue below after removing the existing watch. */
1645 /* This will be false if only attributes of file change. */
1646 bool new_watch
= fspec
->wd
< 0 || new_wd
!= fspec
->wd
;
1652 inotify_rm_watch (wd
, fspec
->wd
);
1653 hash_delete (wd_to_name
, fspec
);
1661 /* If the file was moved then inotify will use the source file wd
1662 for the destination file. Make sure the key is not present in
1664 struct File_spec
*prev
= hash_delete (wd_to_name
, fspec
);
1665 if (prev
&& prev
!= fspec
)
1667 if (follow_mode
== Follow_name
)
1668 recheck (prev
, false);
1670 close_fd (prev
->fd
, pretty_name (prev
));
1673 if (hash_insert (wd_to_name
, fspec
) == NULL
)
1677 if (follow_mode
== Follow_name
)
1678 recheck (fspec
, false);
1682 struct File_spec key
;
1684 fspec
= hash_lookup (wd_to_name
, &key
);
1690 if (ev
->mask
& (IN_ATTRIB
| IN_DELETE_SELF
| IN_MOVE_SELF
))
1692 /* Note for IN_MOVE_SELF (the file we're watching has
1693 been clobbered via a rename) we leave the watch
1694 in place since it may still be part of the set
1695 of watched names. */
1696 if (ev
->mask
& IN_DELETE_SELF
)
1698 inotify_rm_watch (wd
, fspec
->wd
);
1699 hash_delete (wd_to_name
, fspec
);
1702 recheck (fspec
, false);
1706 check_fspec (fspec
, ev
->wd
, &prev_wd
);
1711 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1712 Return true if successful. */
1715 tail_bytes (const char *pretty_filename
, int fd
, uintmax_t n_bytes
,
1716 uintmax_t *read_pos
)
1720 if (fstat (fd
, &stats
))
1722 error (0, errno
, _("cannot fstat %s"), quote (pretty_filename
));
1728 if ( ! presume_input_pipe
1729 && S_ISREG (stats
.st_mode
) && n_bytes
<= OFF_T_MAX
)
1731 xlseek (fd
, n_bytes
, SEEK_CUR
, pretty_filename
);
1732 *read_pos
+= n_bytes
;
1736 int t
= start_bytes (pretty_filename
, fd
, n_bytes
, read_pos
);
1740 n_bytes
= COPY_TO_EOF
;
1744 off_t end_pos
= ((! presume_input_pipe
&& usable_st_size (&stats
)
1745 && n_bytes
<= OFF_T_MAX
)
1746 ? stats
.st_size
: -1);
1747 if (end_pos
<= ST_BLKSIZE (stats
))
1748 return pipe_bytes (pretty_filename
, fd
, n_bytes
, read_pos
);
1749 off_t current_pos
= xlseek (fd
, 0, SEEK_CUR
, pretty_filename
);
1750 if (current_pos
< end_pos
)
1752 off_t bytes_remaining
= end_pos
- current_pos
;
1754 if (n_bytes
< bytes_remaining
)
1756 current_pos
= end_pos
- n_bytes
;
1757 xlseek (fd
, current_pos
, SEEK_SET
, pretty_filename
);
1760 *read_pos
= current_pos
;
1763 *read_pos
+= dump_remainder (pretty_filename
, fd
, n_bytes
);
1767 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1768 Return true if successful. */
1771 tail_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
1772 uintmax_t *read_pos
)
1776 if (fstat (fd
, &stats
))
1778 error (0, errno
, _("cannot fstat %s"), quote (pretty_filename
));
1784 int t
= start_lines (pretty_filename
, fd
, n_lines
, read_pos
);
1787 *read_pos
+= dump_remainder (pretty_filename
, fd
, COPY_TO_EOF
);
1791 off_t start_pos
= -1;
1794 /* Use file_lines only if FD refers to a regular file for
1795 which lseek (... SEEK_END) works. */
1796 if ( ! presume_input_pipe
1797 && S_ISREG (stats
.st_mode
)
1798 && (start_pos
= lseek (fd
, 0, SEEK_CUR
)) != -1
1799 && start_pos
< (end_pos
= lseek (fd
, 0, SEEK_END
)))
1801 *read_pos
= end_pos
;
1803 && ! file_lines (pretty_filename
, fd
, n_lines
,
1804 start_pos
, end_pos
, read_pos
))
1809 /* Under very unlikely circumstances, it is possible to reach
1810 this point after positioning the file pointer to end of file
1811 via the 'lseek (...SEEK_END)' above. In that case, reposition
1812 the file pointer back to start_pos before calling pipe_lines. */
1813 if (start_pos
!= -1)
1814 xlseek (fd
, start_pos
, SEEK_SET
, pretty_filename
);
1816 return pipe_lines (pretty_filename
, fd
, n_lines
, read_pos
);
1822 /* Display the last N_UNITS units of file FILENAME, open for reading
1823 via FD. Set *READ_POS to the position of the input stream pointer.
1824 *READ_POS is usually the number of bytes read and corresponds to an
1825 offset from the beginning of a file. However, it may be larger than
1826 OFF_T_MAX (as for an input pipe), and may also be larger than the
1827 number of bytes read (when an input pointer is initially not at
1828 beginning of file), and may be far greater than the number of bytes
1829 actually read for an input file that is seekable.
1830 Return true if successful. */
1833 tail (const char *filename
, int fd
, uintmax_t n_units
,
1834 uintmax_t *read_pos
)
1838 return tail_lines (filename
, fd
, n_units
, read_pos
);
1840 return tail_bytes (filename
, fd
, n_units
, read_pos
);
1843 /* Display the last N_UNITS units of the file described by F.
1844 Return true if successful. */
1847 tail_file (struct File_spec
*f
, uintmax_t n_units
)
1852 bool is_stdin
= (STREQ (f
->name
, "-"));
1856 have_read_stdin
= true;
1858 if (O_BINARY
&& ! isatty (STDIN_FILENO
))
1859 xfreopen (NULL
, "rb", stdin
);
1862 fd
= open (f
->name
, O_RDONLY
| O_BINARY
);
1864 f
->tailable
= !(reopen_inaccessible_files
&& fd
== -1);
1876 error (0, errno
, _("cannot open %s for reading"),
1877 quote (pretty_name (f
)));
1885 write_header (pretty_name (f
));
1886 ok
= tail (pretty_name (f
), fd
, n_units
, &read_pos
);
1892 /* Before the tail function provided 'read_pos', there was
1893 a race condition described in the URL below. This sleep
1894 call made the window big enough to exercise the problem. */
1898 if (fstat (fd
, &stats
) < 0)
1902 error (0, errno
, _("error reading %s"), quote (pretty_name (f
)));
1904 else if (!IS_TAILABLE_FILE_TYPE (stats
.st_mode
))
1906 error (0, 0, _("%s: cannot follow end of this type of file;\
1907 giving up on this name"),
1916 close_fd (fd
, pretty_name (f
));
1921 /* Note: we must use read_pos here, not stats.st_size,
1922 to avoid a race condition described by Ken Raeburn:
1923 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1924 record_open_fd (f
, fd
, read_pos
, &stats
, (is_stdin
? -1 : 1));
1925 f
->remote
= fremote (fd
, pretty_name (f
));
1930 if (!is_stdin
&& close (fd
))
1932 error (0, errno
, _("error reading %s"), quote (pretty_name (f
)));
1941 /* If obsolete usage is allowed, and the command line arguments are of
1942 the obsolete form and the option string is well-formed, set
1943 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1944 return true. If the command line arguments are obviously incorrect
1945 (e.g., because obsolete usage is not allowed and the arguments are
1946 incorrect for non-obsolete usage), report an error and exit.
1947 Otherwise, return false and don't modify any parameter or global
1951 parse_obsolete_option (int argc
, char * const *argv
, uintmax_t *n_units
)
1954 const char *n_string
;
1955 const char *n_string_end
;
1956 bool obsolete_usage
;
1957 int default_count
= DEFAULT_N_LINES
;
1959 bool t_count_lines
= true;
1960 bool t_forever
= false;
1962 /* With the obsolete form, there is one option string and at most
1963 one file argument. Watch out for "-" and "--", though. */
1965 || (argc
== 3 && ! (argv
[2][0] == '-' && argv
[2][1]))
1966 || (3 <= argc
&& argc
<= 4 && STREQ (argv
[2], "--"))))
1969 obsolete_usage
= (posix2_version () < 200112);
1978 /* Leading "+" is a file name in the non-obsolete form. */
1979 if (!obsolete_usage
)
1982 t_from_start
= true;
1986 /* In the non-obsolete form, "-" is standard input and "-c"
1987 requires an option-argument. The obsolete multidigit options
1988 are supported as a GNU extension even when conforming to
1989 POSIX 1003.1-2001, so don't complain about them. */
1990 if (!obsolete_usage
&& !p
[p
[0] == 'c'])
1993 t_from_start
= false;
1998 while (ISDIGIT (*p
))
2004 case 'b': default_count
*= 512; /* Fall through. */
2005 case 'c': t_count_lines
= false; /* Fall through. */
2006 case 'l': p
++; break;
2018 if (n_string
== n_string_end
)
2019 *n_units
= default_count
;
2020 else if ((xstrtoumax (n_string
, NULL
, 10, n_units
, "b")
2021 & ~LONGINT_INVALID_SUFFIX_CHAR
)
2024 error (EXIT_FAILURE
, errno
, "%s: %s", _("invalid number"),
2029 from_start
= t_from_start
;
2030 count_lines
= t_count_lines
;
2031 forever
= t_forever
;
2037 parse_options (int argc
, char **argv
,
2038 uintmax_t *n_units
, enum header_mode
*header_mode
,
2039 double *sleep_interval
)
2043 while ((c
= getopt_long (argc
, argv
, "c:n:fFqs:v0123456789",
2044 long_options
, NULL
))
2051 follow_mode
= Follow_name
;
2052 reopen_inaccessible_files
= true;
2057 count_lines
= (c
== 'n');
2060 else if (*optarg
== '-')
2063 *n_units
= xdectoumax (optarg
, 0, UINTMAX_MAX
, "bkKmMGTPEZY0",
2065 ? _("invalid number of lines")
2066 : _("invalid number of bytes"), 0);
2070 case LONG_FOLLOW_OPTION
:
2073 follow_mode
= DEFAULT_FOLLOW_MODE
;
2075 follow_mode
= XARGMATCH ("--follow", optarg
,
2076 follow_mode_string
, follow_mode_map
);
2080 reopen_inaccessible_files
= true;
2083 case MAX_UNCHANGED_STATS_OPTION
:
2084 /* --max-unchanged-stats=N */
2085 max_n_unchanged_stats_between_opens
=
2086 xdectoumax (optarg
, 0, UINTMAX_MAX
, "",
2087 _("invalid maximum number of unchanged stats between opens"), 0);
2090 case DISABLE_INOTIFY_OPTION
:
2091 disable_inotify
= true;
2095 pid
= xdectoumax (optarg
, 0, PID_T_MAX
, "", _("invalid PID"), 0);
2098 case PRESUME_INPUT_PIPE_OPTION
:
2099 presume_input_pipe
= true;
2103 *header_mode
= never
;
2109 if (! (xstrtod (optarg
, NULL
, &s
, c_strtod
) && 0 <= s
))
2110 error (EXIT_FAILURE
, 0,
2111 _("invalid number of seconds: %s"), quote (optarg
));
2112 *sleep_interval
= s
;
2117 *header_mode
= always
;
2120 case_GETOPT_HELP_CHAR
;
2122 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
2124 case '0': case '1': case '2': case '3': case '4':
2125 case '5': case '6': case '7': case '8': case '9':
2126 error (EXIT_FAILURE
, 0,
2127 _("option used in invalid context -- %c"), c
);
2130 usage (EXIT_FAILURE
);
2134 if (reopen_inaccessible_files
)
2138 reopen_inaccessible_files
= false;
2139 error (0, 0, _("warning: --retry ignored; --retry is useful"
2140 " only when following"));
2142 else if (follow_mode
== Follow_descriptor
)
2143 error (0, 0, _("warning: --retry only effective for the initial open"));
2146 if (pid
&& !forever
)
2148 _("warning: PID ignored; --pid=PID is useful only when following"));
2149 else if (pid
&& kill (pid
, 0) != 0 && errno
== ENOSYS
)
2151 error (0, 0, _("warning: --pid=PID is not supported on this system"));
2156 /* Mark as '.ignore'd each member of F that corresponds to a
2157 pipe or fifo, and return the number of non-ignored members. */
2159 ignore_fifo_and_pipe (struct File_spec
*f
, size_t n_files
)
2161 /* When there is no FILE operand and stdin is a pipe or FIFO
2162 POSIX requires that tail ignore the -f option.
2163 Since we allow multiple FILE operands, we extend that to say: with -f,
2164 ignore any "-" operand that corresponds to a pipe or FIFO. */
2165 size_t n_viable
= 0;
2168 for (i
= 0; i
< n_files
; i
++)
2170 bool is_a_fifo_or_pipe
=
2171 (STREQ (f
[i
].name
, "-")
2174 && (S_ISFIFO (f
[i
].mode
)
2175 || (HAVE_FIFO_PIPES
!= 1 && isapipe (f
[i
].fd
))));
2176 if (is_a_fifo_or_pipe
)
2186 main (int argc
, char **argv
)
2188 enum header_mode header_mode
= multiple_files
;
2190 /* If from_start, the number of items to skip before printing; otherwise,
2191 the number of items at the end of the file to print. Although the type
2192 is signed, the value is never negative. */
2193 uintmax_t n_units
= DEFAULT_N_LINES
;
2196 struct File_spec
*F
;
2198 bool obsolete_option
;
2200 /* The number of seconds to sleep between iterations.
2201 During one iteration, every file name or descriptor is checked to
2202 see if it has changed. */
2203 double sleep_interval
= 1.0;
2205 initialize_main (&argc
, &argv
);
2206 set_program_name (argv
[0]);
2207 setlocale (LC_ALL
, "");
2208 bindtextdomain (PACKAGE
, LOCALEDIR
);
2209 textdomain (PACKAGE
);
2211 atexit (close_stdout
);
2213 have_read_stdin
= false;
2216 forever
= from_start
= print_headers
= false;
2217 obsolete_option
= parse_obsolete_option (argc
, argv
, &n_units
);
2218 argc
-= obsolete_option
;
2219 argv
+= obsolete_option
;
2220 parse_options (argc
, argv
, &n_units
, &header_mode
, &sleep_interval
);
2222 /* To start printing with item N_UNITS from the start of the file, skip
2223 N_UNITS - 1 items. 'tail -n +0' is actually meaningless, but for Unix
2224 compatibility it's treated the same as 'tail -n +1'. */
2231 IF_LINT (assert (0 <= argc
));
2235 n_files
= argc
- optind
;
2236 file
= argv
+ optind
;
2240 static char *dummy_stdin
= (char *) "-";
2242 file
= &dummy_stdin
;
2246 bool found_hyphen
= false;
2248 for (i
= 0; i
< n_files
; i
++)
2249 if (STREQ (file
[i
], "-"))
2250 found_hyphen
= true;
2252 /* When following by name, there must be a name. */
2253 if (found_hyphen
&& follow_mode
== Follow_name
)
2254 error (EXIT_FAILURE
, 0, _("cannot follow %s by name"), quote ("-"));
2256 /* When following forever, warn if any file is '-'.
2257 This is only a warning, since tail's output (before a failing seek,
2258 and that from any non-stdin files) might still be useful. */
2259 if (forever
&& found_hyphen
&& isatty (STDIN_FILENO
))
2260 error (0, 0, _("warning: following standard input"
2261 " indefinitely is ineffective"));
2264 /* Don't read anything if we'll never output anything. */
2265 if (! n_units
&& ! forever
&& ! from_start
)
2266 return EXIT_SUCCESS
;
2268 F
= xnmalloc (n_files
, sizeof *F
);
2269 for (i
= 0; i
< n_files
; i
++)
2270 F
[i
].name
= file
[i
];
2272 if (header_mode
== always
2273 || (header_mode
== multiple_files
&& n_files
> 1))
2274 print_headers
= true;
2276 if (O_BINARY
&& ! isatty (STDOUT_FILENO
))
2277 xfreopen (NULL
, "wb", stdout
);
2279 for (i
= 0; i
< n_files
; i
++)
2280 ok
&= tail_file (&F
[i
], n_units
);
2282 if (forever
&& ignore_fifo_and_pipe (F
, n_files
))
2285 /* tailable_stdin() checks if the user specifies stdin via "-",
2286 or implicitly by providing no arguments. If so, we won't use inotify.
2287 Technically, on systems with a working /dev/stdin, we *could*,
2288 but would it be worth it? Verifying that it's a real device
2289 and hooked up to stdin is not trivial, while reverting to
2290 non-inotify-based tail_forever is easy and portable.
2292 any_remote_file() checks if the user has specified any
2293 files that reside on remote file systems. inotify is not used
2294 in this case because it would miss any updates to the file
2295 that were not initiated from the local system.
2297 any_symlinks() checks if the user has specified any symbolic links.
2298 inotify is not used in this case because it returns updated _targets_
2299 which would not match the specified names. If we tried to always
2300 use the target names, then we would miss changes to the symlink itself.
2302 ok is false when one of the files specified could not be opened for
2303 reading. In this case and when following by descriptor,
2304 tail_forever_inotify() cannot be used (in its current implementation).
2306 FIXME: inotify doesn't give any notification when a new
2307 (remote) file or directory is mounted on top a watched file.
2308 When follow_mode == Follow_name we would ideally like to detect that.
2309 Note if there is a change to the original file then we'll
2310 recheck it and follow the new file, or ignore it if the
2311 file has changed to being remote.
2313 FIXME: when using inotify, and a directory for a watched file
2314 is recreated, then we don't recheck any new file when
2315 follow_mode == Follow_name.
2317 FIXME-maybe: inotify has a watch descriptor per inode, and hence with
2318 our current hash implementation will only --follow data for one
2319 of the names when multiple hardlinked files are specified. */
2320 if (!disable_inotify
&& (tailable_stdin (F
, n_files
)
2321 || any_remote_file (F
, n_files
)
2322 || any_symlinks (F
, n_files
)
2323 || (!ok
&& follow_mode
== Follow_descriptor
)))
2324 disable_inotify
= true;
2326 if (!disable_inotify
)
2328 int wd
= inotify_init ();
2331 /* Flush any output from tail_file, now, since
2332 tail_forever_inotify flushes only after writing,
2333 not before reading. */
2334 if (fflush (stdout
) != 0)
2335 error (EXIT_FAILURE
, errno
, _("write error"));
2337 if (! tail_forever_inotify (wd
, F
, n_files
, sleep_interval
))
2338 return EXIT_FAILURE
;
2340 error (0, errno
, _("inotify cannot be used, reverting to polling"));
2342 /* Free resources as this process can be long lived,
2343 and we may have exhausted system resources above. */
2345 for (i
= 0; i
< n_files
; i
++)
2347 /* It's OK to remove the same watch multiple times,
2348 ignoring the EINVAL from redundant calls. */
2350 inotify_rm_watch (wd
, F
[i
].wd
);
2351 if (F
[i
].parent_wd
!= -1)
2352 inotify_rm_watch (wd
, F
[i
].parent_wd
);
2356 disable_inotify
= true;
2357 tail_forever (F
, n_files
, sleep_interval
);
2360 if (have_read_stdin
&& close (STDIN_FILENO
) < 0)
2361 error (EXIT_FAILURE
, errno
, "-");
2362 return ok
? EXIT_SUCCESS
: EXIT_FAILURE
;