1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989-1991, 1995-2006, 2008-2012 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-time.h"
45 #include "xnanosleep.h"
51 # include <sys/inotify.h>
52 /* 'select' is used by tail_forever_inotify. */
53 # include <sys/select.h>
55 /* inotify needs to know if a file is local. */
57 # include "fs-is-local.h"
58 # if HAVE_SYS_STATFS_H
59 # include <sys/statfs.h>
65 /* The official name of this program (e.g., no 'g' prefix). */
66 #define PROGRAM_NAME "tail"
69 proper_name ("Paul Rubin"), \
70 proper_name ("David MacKenzie"), \
71 proper_name ("Ian Lance Taylor"), \
72 proper_name ("Jim Meyering")
74 /* Number of items to tail. */
75 #define DEFAULT_N_LINES 10
77 /* Special values for dump_remainder's N_BYTES parameter. */
78 #define COPY_TO_EOF UINTMAX_MAX
79 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
81 /* FIXME: make Follow_name the default? */
82 #define DEFAULT_FOLLOW_MODE Follow_descriptor
86 /* Follow the name of each file: if the file is renamed, try to reopen
87 that name and track the end of the new file if/when it's recreated.
88 This is useful for tracking logs that are occasionally rotated. */
91 /* Follow each descriptor obtained upon opening a file.
92 That means we'll continue to follow the end of a file even after
93 it has been renamed or unlinked. */
97 /* The types of files for which tail works. */
98 #define IS_TAILABLE_FILE_TYPE(Mode) \
99 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
101 static char const *const follow_mode_string
[] =
103 "descriptor", "name", NULL
106 static enum Follow_mode
const follow_mode_map
[] =
108 Follow_descriptor
, Follow_name
,
113 /* The actual file name, or "-" for stdin. */
116 /* Attributes of the file the last time we checked. */
118 struct timespec mtime
;
123 /* The specified name initially referred to a directory or some other
124 type for which tail isn't meaningful. Unlike for a permission problem
125 (tailable, below) once this is set, the name is not checked ever again. */
128 /* See the description of fremote. */
131 /* A file is tailable if it exists, is readable, and is of type
132 IS_TAILABLE_FILE_TYPE. */
135 /* File descriptor on which the file is open; -1 if it's not open. */
138 /* The value of errno seen last time we checked this file. */
141 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
145 /* The watch descriptor used by inotify. */
148 /* The parent directory watch descriptor. It is used only
149 * when Follow_name is used. */
152 /* Offset in NAME of the basename part. */
153 size_t basename_start
;
156 /* See description of DEFAULT_MAX_N_... below. */
157 uintmax_t n_unchanged_stats
;
161 /* The events mask used with inotify on files. This mask is not used on
163 static const uint32_t inotify_wd_mask
= (IN_MODIFY
| IN_ATTRIB
164 | IN_DELETE_SELF
| IN_MOVE_SELF
);
167 /* Keep trying to open a file even if it is inaccessible when tail starts
168 or if it becomes inaccessible later -- useful only with -f. */
169 static bool reopen_inaccessible_files
;
171 /* If true, interpret the numeric argument as the number of lines.
172 Otherwise, interpret it as the number of bytes. */
173 static bool count_lines
;
175 /* Whether we follow the name of each file or the file descriptor
176 that is initially associated with each name. */
177 static enum Follow_mode follow_mode
= Follow_descriptor
;
179 /* If true, read from the ends of all specified files until killed. */
182 /* If true, count from start of file instead of end. */
183 static bool from_start
;
185 /* If true, print filename headers. */
186 static bool print_headers
;
188 /* When to print the filename banners. */
191 multiple_files
, always
, never
194 /* When tailing a file by name, if there have been this many consecutive
195 iterations for which the file has not changed, then open/fstat
196 the file to determine if that file name is still associated with the
197 same device/inode-number pair as before. This option is meaningful only
198 when following by name. --max-unchanged-stats=N */
199 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
200 static uintmax_t max_n_unchanged_stats_between_opens
=
201 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
;
203 /* The process ID of the process (presumably on the current host)
204 that is writing to all followed files. */
207 /* True if we have ever read standard input. */
208 static bool have_read_stdin
;
210 /* If nonzero, skip the is-regular-file test used to determine whether
211 to use the lseek optimization. Instead, use the more general (and
212 more expensive) code unconditionally. Intended solely for testing. */
213 static bool presume_input_pipe
;
215 /* If nonzero then don't use inotify even if available. */
216 static bool disable_inotify
;
218 /* For long options that have no equivalent short option, use a
219 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
222 RETRY_OPTION
= CHAR_MAX
+ 1,
223 MAX_UNCHANGED_STATS_OPTION
,
225 PRESUME_INPUT_PIPE_OPTION
,
227 DISABLE_INOTIFY_OPTION
230 static struct option
const long_options
[] =
232 {"bytes", required_argument
, NULL
, 'c'},
233 {"follow", optional_argument
, NULL
, LONG_FOLLOW_OPTION
},
234 {"lines", required_argument
, NULL
, 'n'},
235 {"max-unchanged-stats", required_argument
, NULL
, MAX_UNCHANGED_STATS_OPTION
},
236 {"-disable-inotify", no_argument
, NULL
,
237 DISABLE_INOTIFY_OPTION
}, /* do not document */
238 {"pid", required_argument
, NULL
, PID_OPTION
},
239 {"-presume-input-pipe", no_argument
, NULL
,
240 PRESUME_INPUT_PIPE_OPTION
}, /* do not document */
241 {"quiet", no_argument
, NULL
, 'q'},
242 {"retry", no_argument
, NULL
, RETRY_OPTION
},
243 {"silent", no_argument
, NULL
, 'q'},
244 {"sleep-interval", required_argument
, NULL
, 's'},
245 {"verbose", no_argument
, NULL
, 'v'},
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 With no FILE, or when FILE is -, read standard input.\n\
267 "), DEFAULT_N_LINES
);
269 Mandatory arguments to long options are mandatory for short options too.\n\
272 -c, --bytes=K output the last K bytes; alternatively, use -c +K\n\
273 to output bytes starting with the Kth of each file\n\
276 -f, --follow[={name|descriptor}]\n\
277 output appended data as the file grows;\n\
278 -f, --follow, and --follow=descriptor are\n\
280 -F same as --follow=name --retry\n\
283 -n, --lines=K output the last K lines, instead of the last %d;\n\
284 or use -n +K to output lines starting with the Kth\n\
285 --max-unchanged-stats=N\n\
286 with --follow=name, reopen a FILE which has not\n\
287 changed size after N (default %d) iterations\n\
288 to see if it has been unlinked or renamed\n\
289 (this is the usual case of rotated log files).\n\
290 With inotify, this option is rarely useful.\n\
293 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
296 --pid=PID with -f, terminate after process ID, PID dies\n\
297 -q, --quiet, --silent never output headers giving file names\n\
298 --retry keep trying to open a file even when it is or\n\
299 becomes inaccessible; useful when following by\n\
300 name, i.e., with --follow=name\n\
303 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
304 (default 1.0) between iterations.\n\
305 With inotify and --pid=P, check process P at\n\
306 least once every N seconds.\n\
307 -v, --verbose always output headers giving file names\n\
309 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
310 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
313 If the first character of K (the number of bytes or lines) is a '+',\n\
314 print beginning with the Kth item from the start of each file, otherwise,\n\
315 print the last K items in the file. K may have a multiplier suffix:\n\
316 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
317 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
321 With --follow (-f), tail defaults to following the file descriptor, which\n\
322 means that even if a tail'ed file is renamed, tail will continue to track\n\
323 its end. This default behavior is not desirable when you really want to\n\
324 track the actual name of the file, not the file descriptor (e.g., log\n\
325 rotation). Use --follow=name in that case. That causes tail to track the\n\
326 named file in a way that accommodates renaming, removal and creation.\n\
328 emit_ancillary_info ();
334 valid_file_spec (struct File_spec
const *f
)
336 /* Exactly one of the following subexpressions must be true. */
337 return ((f
->fd
== -1) ^ (f
->errnum
== 0));
341 pretty_name (struct File_spec
const *f
)
343 return (STREQ (f
->name
, "-") ? _("standard input") : f
->name
);
347 xwrite_stdout (char const *buffer
, size_t n_bytes
)
349 if (n_bytes
> 0 && fwrite (buffer
, 1, n_bytes
, stdout
) == 0)
350 error (EXIT_FAILURE
, errno
, _("write error"));
353 /* Record a file F with descriptor FD, size SIZE, status ST, and
354 blocking status BLOCKING. */
357 record_open_fd (struct File_spec
*f
, int fd
,
358 off_t size
, struct stat
const *st
,
363 f
->mtime
= get_stat_mtime (st
);
366 f
->mode
= st
->st_mode
;
367 f
->blocking
= blocking
;
368 f
->n_unchanged_stats
= 0;
372 /* Close the file with descriptor FD and name FILENAME. */
375 close_fd (int fd
, const char *filename
)
377 if (fd
!= -1 && fd
!= STDIN_FILENO
&& close (fd
))
379 error (0, errno
, _("closing %s (fd=%d)"), filename
, fd
);
384 write_header (const char *pretty_filename
)
386 static bool first_file
= true;
388 printf ("%s==> %s <==\n", (first_file
? "" : "\n"), pretty_filename
);
392 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
393 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
394 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
395 Return the number of bytes read from the file. */
398 dump_remainder (const char *pretty_filename
, int fd
, uintmax_t n_bytes
)
401 uintmax_t n_remaining
= n_bytes
;
407 size_t n
= MIN (n_remaining
, BUFSIZ
);
408 size_t bytes_read
= safe_read (fd
, buffer
, n
);
409 if (bytes_read
== SAFE_READ_ERROR
)
412 error (EXIT_FAILURE
, errno
, _("error reading %s"),
413 quote (pretty_filename
));
418 xwrite_stdout (buffer
, bytes_read
);
419 n_written
+= bytes_read
;
420 if (n_bytes
!= COPY_TO_EOF
)
422 n_remaining
-= bytes_read
;
423 if (n_remaining
== 0 || n_bytes
== COPY_A_BUFFER
)
431 /* Call lseek with the specified arguments, where file descriptor FD
432 corresponds to the file, FILENAME.
433 Give a diagnostic and exit nonzero if lseek fails.
434 Otherwise, return the resulting offset. */
437 xlseek (int fd
, off_t offset
, int whence
, char const *filename
)
439 off_t new_offset
= lseek (fd
, offset
, whence
);
440 char buf
[INT_BUFSIZE_BOUND (offset
)];
446 s
= offtostr (offset
, buf
);
450 error (0, errno
, _("%s: cannot seek to offset %s"),
454 error (0, errno
, _("%s: cannot seek to relative offset %s"),
458 error (0, errno
, _("%s: cannot seek to end-relative offset %s"),
468 /* Print the last N_LINES lines from the end of file FD.
469 Go backward through the file, reading 'BUFSIZ' bytes at a time (except
470 probably the first), until we hit the start of the file or have
471 read NUMBER newlines.
472 START_POS is the starting position of the read pointer for the file
473 associated with FD (may be nonzero).
474 END_POS is the file offset of EOF (one larger than offset of last byte).
475 Return true if successful. */
478 file_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
479 off_t start_pos
, off_t end_pos
, uintmax_t *read_pos
)
488 /* Set 'bytes_read' to the size of the last, probably partial, buffer;
489 0 < 'bytes_read' <= 'BUFSIZ'. */
490 bytes_read
= (pos
- start_pos
) % BUFSIZ
;
493 /* Make 'pos' a multiple of 'BUFSIZ' (0 if the file is short), so that all
494 reads will be on block boundaries, which might increase efficiency. */
496 xlseek (fd
, pos
, SEEK_SET
, pretty_filename
);
497 bytes_read
= safe_read (fd
, buffer
, bytes_read
);
498 if (bytes_read
== SAFE_READ_ERROR
)
500 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
503 *read_pos
= pos
+ bytes_read
;
505 /* Count the incomplete line on files that don't end with a newline. */
506 if (bytes_read
&& buffer
[bytes_read
- 1] != '\n')
511 /* Scan backward, counting the newlines in this bufferfull. */
513 size_t n
= bytes_read
;
517 nl
= memrchr (buffer
, '\n', n
);
523 /* If this newline isn't the last character in the buffer,
524 output the part that is after it. */
525 if (n
!= bytes_read
- 1)
526 xwrite_stdout (nl
+ 1, bytes_read
- (n
+ 1));
527 *read_pos
+= dump_remainder (pretty_filename
, fd
,
528 end_pos
- (pos
+ bytes_read
));
533 /* Not enough newlines in that bufferfull. */
534 if (pos
== start_pos
)
536 /* Not enough lines in the file; print everything from
537 start_pos to the end. */
538 xlseek (fd
, start_pos
, SEEK_SET
, pretty_filename
);
539 *read_pos
= start_pos
+ dump_remainder (pretty_filename
, fd
,
544 xlseek (fd
, pos
, SEEK_SET
, pretty_filename
);
546 bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
547 if (bytes_read
== SAFE_READ_ERROR
)
549 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
553 *read_pos
= pos
+ bytes_read
;
555 while (bytes_read
> 0);
560 /* Print the last N_LINES lines from the end of the standard input,
561 open for reading as pipe FD.
562 Buffer the text as a linked list of LBUFFERs, adding them as needed.
563 Return true if successful. */
566 pipe_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
574 struct linebuffer
*next
;
576 typedef struct linebuffer LBUFFER
;
577 LBUFFER
*first
, *last
, *tmp
;
578 size_t total_lines
= 0; /* Total number of newlines in all buffers. */
580 size_t n_read
; /* Size in bytes of most recent read */
582 first
= last
= xmalloc (sizeof (LBUFFER
));
583 first
->nbytes
= first
->nlines
= 0;
585 tmp
= xmalloc (sizeof (LBUFFER
));
587 /* Input is always read into a fresh buffer. */
590 n_read
= safe_read (fd
, tmp
->buffer
, BUFSIZ
);
591 if (n_read
== 0 || n_read
== SAFE_READ_ERROR
)
593 tmp
->nbytes
= n_read
;
598 /* Count the number of newlines just read. */
600 char const *buffer_end
= tmp
->buffer
+ n_read
;
601 char const *p
= tmp
->buffer
;
602 while ((p
= memchr (p
, '\n', buffer_end
- p
)))
608 total_lines
+= tmp
->nlines
;
610 /* If there is enough room in the last buffer read, just append the new
611 one to it. This is because when reading from a pipe, 'n_read' can
612 often be very small. */
613 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
615 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
616 last
->nbytes
+= tmp
->nbytes
;
617 last
->nlines
+= tmp
->nlines
;
621 /* If there's not enough room, link the new buffer onto the end of
622 the list, then either free up the oldest buffer for the next
623 read if that would leave enough lines, or else malloc a new one.
624 Some compaction mechanism is possible but probably not
626 last
= last
->next
= tmp
;
627 if (total_lines
- first
->nlines
> n_lines
)
630 total_lines
-= first
->nlines
;
634 tmp
= xmalloc (sizeof (LBUFFER
));
640 if (n_read
== SAFE_READ_ERROR
)
642 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
647 /* If the file is empty, then bail out. */
648 if (last
->nbytes
== 0)
651 /* This prevents a core dump when the pipe contains no newlines. */
655 /* Count the incomplete line on files that don't end with a newline. */
656 if (last
->buffer
[last
->nbytes
- 1] != '\n')
662 /* Run through the list, printing lines. First, skip over unneeded
664 for (tmp
= first
; total_lines
- tmp
->nlines
> n_lines
; tmp
= tmp
->next
)
665 total_lines
-= tmp
->nlines
;
667 /* Find the correct beginning, then print the rest of the file. */
669 char const *beg
= tmp
->buffer
;
670 char const *buffer_end
= tmp
->buffer
+ tmp
->nbytes
;
671 if (total_lines
> n_lines
)
673 /* Skip 'total_lines' - 'n_lines' newlines. We made sure that
674 'total_lines' - 'n_lines' <= 'tmp->nlines'. */
676 for (j
= total_lines
- n_lines
; j
; --j
)
678 beg
= memchr (beg
, '\n', buffer_end
- beg
);
684 xwrite_stdout (beg
, buffer_end
- beg
);
687 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
688 xwrite_stdout (tmp
->buffer
, tmp
->nbytes
);
700 /* Print the last N_BYTES characters from the end of pipe FD.
701 This is a stripped down version of pipe_lines.
702 Return true if successful. */
705 pipe_bytes (const char *pretty_filename
, int fd
, uintmax_t n_bytes
,
712 struct charbuffer
*next
;
714 typedef struct charbuffer CBUFFER
;
715 CBUFFER
*first
, *last
, *tmp
;
716 size_t i
; /* Index into buffers. */
717 size_t total_bytes
= 0; /* Total characters in all buffers. */
721 first
= last
= xmalloc (sizeof (CBUFFER
));
724 tmp
= xmalloc (sizeof (CBUFFER
));
726 /* Input is always read into a fresh buffer. */
729 n_read
= safe_read (fd
, tmp
->buffer
, BUFSIZ
);
730 if (n_read
== 0 || n_read
== SAFE_READ_ERROR
)
733 tmp
->nbytes
= n_read
;
736 total_bytes
+= tmp
->nbytes
;
737 /* If there is enough room in the last buffer read, just append the new
738 one to it. This is because when reading from a pipe, 'nbytes' can
739 often be very small. */
740 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
742 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
743 last
->nbytes
+= tmp
->nbytes
;
747 /* If there's not enough room, link the new buffer onto the end of
748 the list, then either free up the oldest buffer for the next
749 read if that would leave enough characters, or else malloc a new
750 one. Some compaction mechanism is possible but probably not
752 last
= last
->next
= tmp
;
753 if (total_bytes
- first
->nbytes
> n_bytes
)
756 total_bytes
-= first
->nbytes
;
761 tmp
= xmalloc (sizeof (CBUFFER
));
768 if (n_read
== SAFE_READ_ERROR
)
770 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
775 /* Run through the list, printing characters. First, skip over unneeded
777 for (tmp
= first
; total_bytes
- tmp
->nbytes
> n_bytes
; tmp
= tmp
->next
)
778 total_bytes
-= tmp
->nbytes
;
780 /* Find the correct beginning, then print the rest of the file.
781 We made sure that 'total_bytes' - 'n_bytes' <= 'tmp->nbytes'. */
782 if (total_bytes
> n_bytes
)
783 i
= total_bytes
- n_bytes
;
786 xwrite_stdout (&tmp
->buffer
[i
], tmp
->nbytes
- i
);
788 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
789 xwrite_stdout (tmp
->buffer
, tmp
->nbytes
);
801 /* Skip N_BYTES characters from the start of pipe FD, and print
802 any extra characters that were read beyond that.
803 Return 1 on error, 0 if ok, -1 if EOF. */
806 start_bytes (const char *pretty_filename
, int fd
, uintmax_t n_bytes
,
813 size_t bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
816 if (bytes_read
== SAFE_READ_ERROR
)
818 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
821 *read_pos
+= bytes_read
;
822 if (bytes_read
<= n_bytes
)
823 n_bytes
-= bytes_read
;
826 size_t n_remaining
= bytes_read
- n_bytes
;
828 xwrite_stdout (&buffer
[n_bytes
], n_remaining
);
836 /* Skip N_LINES lines at the start of file or pipe FD, and print
837 any extra characters that were read beyond that.
838 Return 1 on error, 0 if ok, -1 if EOF. */
841 start_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
850 size_t bytes_read
= safe_read (fd
, buffer
, BUFSIZ
);
851 if (bytes_read
== 0) /* EOF */
853 if (bytes_read
== SAFE_READ_ERROR
) /* error */
855 error (0, errno
, _("error reading %s"), quote (pretty_filename
));
859 char *buffer_end
= buffer
+ bytes_read
;
861 *read_pos
+= bytes_read
;
864 while ((p
= memchr (p
, '\n', buffer_end
- p
)))
870 xwrite_stdout (p
, buffer_end
- p
);
878 /* Without inotify support, always return false. Otherwise, return false
879 when FD is open on a file known to reside on a local file system.
880 If fstatfs fails, give a diagnostic and return true.
881 If fstatfs cannot be called, return true. */
883 fremote (int fd
, const char *name
)
885 bool remote
= true; /* be conservative (poll by default). */
887 # if HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE && defined __linux__
889 int err
= fstatfs (fd
, &buf
);
892 /* On at least linux-2.6.38, fstatfs fails with ENOSYS when FD
893 is open on a pipe. Treat that like a remote file. */
895 error (0, errno
, _("cannot determine location of %s. "
896 "reverting to polling"), quote (name
));
900 switch (is_local_fs_type (buf
.f_type
))
906 unsigned long int fs_type
= buf
.f_type
;
907 error (0, 0, _("unrecognized file system type 0x%08lx for %s. "
908 "please report this to %s. reverting to polling"),
909 fs_type
, quote (name
), PACKAGE_BUGREPORT
);
910 /* Treat as "remote", so caller polls. */
917 assert (!"unexpected return value from is_local_fs_type");
925 /* Without inotify support, whether a file is remote is irrelevant.
926 Always return "false" in that case. */
927 # define fremote(fd, name) false
930 /* FIXME: describe */
933 recheck (struct File_spec
*f
, bool blocking
)
935 /* open/fstat the file and announce if dev/ino have changed */
936 struct stat new_stats
;
938 bool is_stdin
= (STREQ (f
->name
, "-"));
939 bool was_tailable
= f
->tailable
;
940 int prev_errnum
= f
->errnum
;
944 : open (f
->name
, O_RDONLY
| (blocking
? 0 : O_NONBLOCK
)));
946 assert (valid_file_spec (f
));
948 /* If the open fails because the file doesn't exist,
949 then mark the file as not tailable. */
950 f
->tailable
= !(reopen_inaccessible_files
&& fd
== -1);
952 if (fd
== -1 || fstat (fd
, &new_stats
) < 0)
960 /* FIXME-maybe: detect the case in which the file first becomes
961 unreadable (perms), and later becomes readable again and can
962 be seen to be the same file (dev/ino). Otherwise, tail prints
963 the entire contents of the file when it becomes readable. */
964 error (0, f
->errnum
, _("%s has become inaccessible"),
965 quote (pretty_name (f
)));
969 /* say nothing... it's still not tailable */
972 else if (prev_errnum
!= errno
)
974 error (0, errno
, "%s", pretty_name (f
));
977 else if (!IS_TAILABLE_FILE_TYPE (new_stats
.st_mode
))
981 error (0, 0, _("%s has been replaced with an untailable file;\
982 giving up on this name"),
983 quote (pretty_name (f
)));
986 else if (!disable_inotify
&& fremote (fd
, pretty_name (f
)))
990 error (0, 0, _("%s has been replaced with a remote file. "
991 "giving up on this name"), quote (pretty_name (f
)));
1003 close_fd (fd
, pretty_name (f
));
1004 close_fd (f
->fd
, pretty_name (f
));
1007 else if (prev_errnum
&& prev_errnum
!= ENOENT
)
1010 assert (f
->fd
== -1);
1011 error (0, 0, _("%s has become accessible"), quote (pretty_name (f
)));
1013 else if (f
->ino
!= new_stats
.st_ino
|| f
->dev
!= new_stats
.st_dev
)
1019 _("%s has appeared; following end of new file"),
1020 quote (pretty_name (f
)));
1024 /* Close the old one. */
1025 close_fd (f
->fd
, pretty_name (f
));
1027 /* File has been replaced (e.g., via log rotation) --
1028 tail the new one. */
1030 _("%s has been replaced; following end of new file"),
1031 quote (pretty_name (f
)));
1038 /* This happens when one iteration finds the file missing,
1039 then the preceding <dev,inode> pair is reused as the
1040 file is recreated. */
1045 close_fd (fd
, pretty_name (f
));
1051 /* Start at the beginning of the file. */
1052 record_open_fd (f
, fd
, 0, &new_stats
, (is_stdin
? -1 : blocking
));
1053 xlseek (fd
, 0, SEEK_SET
, pretty_name (f
));
1057 /* Return true if any of the N_FILES files in F are live, i.e., have
1058 open file descriptors. */
1061 any_live_files (const struct File_spec
*f
, size_t n_files
)
1065 for (i
= 0; i
< n_files
; i
++)
1071 /* Tail N_FILES files forever, or until killed.
1072 The pertinent information for each file is stored in an entry of F.
1073 Loop over each of them, doing an fstat to see if they have changed size,
1074 and an occasional open/fstat to see if any dev/ino pair has changed.
1075 If none of them have changed size in one iteration, sleep for a
1076 while and try again. Continue until the user interrupts us. */
1079 tail_forever (struct File_spec
*f
, size_t n_files
, double sleep_interval
)
1081 /* Use blocking I/O as an optimization, when it's easy. */
1082 bool blocking
= (pid
== 0 && follow_mode
== Follow_descriptor
1083 && n_files
== 1 && ! S_ISREG (f
[0].mode
));
1085 bool writer_is_dead
= false;
1092 bool any_input
= false;
1094 for (i
= 0; i
< n_files
; i
++)
1100 uintmax_t bytes_read
;
1107 recheck (&f
[i
], blocking
);
1112 name
= pretty_name (&f
[i
]);
1115 if (f
[i
].blocking
!= blocking
)
1117 int old_flags
= fcntl (fd
, F_GETFL
);
1118 int new_flags
= old_flags
| (blocking
? 0 : O_NONBLOCK
);
1120 || (new_flags
!= old_flags
1121 && fcntl (fd
, F_SETFL
, new_flags
) == -1))
1123 /* Don't update f[i].blocking if fcntl fails. */
1124 if (S_ISREG (f
[i
].mode
) && errno
== EPERM
)
1126 /* This happens when using tail -f on a file with
1127 the append-only attribute. */
1130 error (EXIT_FAILURE
, errno
,
1131 _("%s: cannot change nonblocking mode"), name
);
1134 f
[i
].blocking
= blocking
;
1139 if (fstat (fd
, &stats
) != 0)
1142 f
[i
].errnum
= errno
;
1143 error (0, errno
, "%s", name
);
1147 if (f
[i
].mode
== stats
.st_mode
1148 && (! S_ISREG (stats
.st_mode
) || f
[i
].size
== stats
.st_size
)
1149 && timespec_cmp (f
[i
].mtime
, get_stat_mtime (&stats
)) == 0)
1151 if ((max_n_unchanged_stats_between_opens
1152 <= f
[i
].n_unchanged_stats
++)
1153 && follow_mode
== Follow_name
)
1155 recheck (&f
[i
], f
[i
].blocking
);
1156 f
[i
].n_unchanged_stats
= 0;
1161 /* This file has changed. Print out what we can, and
1162 then keep looping. */
1164 f
[i
].mtime
= get_stat_mtime (&stats
);
1165 f
[i
].mode
= stats
.st_mode
;
1168 f
[i
].n_unchanged_stats
= 0;
1170 if (S_ISREG (mode
) && stats
.st_size
< f
[i
].size
)
1172 error (0, 0, _("%s: file truncated"), name
);
1174 xlseek (fd
, stats
.st_size
, SEEK_SET
, name
);
1175 f
[i
].size
= stats
.st_size
;
1182 write_header (name
);
1187 bytes_read
= dump_remainder (name
, fd
,
1189 ? COPY_A_BUFFER
: COPY_TO_EOF
));
1190 any_input
|= (bytes_read
!= 0);
1191 f
[i
].size
+= bytes_read
;
1194 if (! any_live_files (f
, n_files
) && ! reopen_inaccessible_files
)
1196 error (0, 0, _("no files remaining"));
1200 if ((!any_input
|| blocking
) && fflush (stdout
) != 0)
1201 error (EXIT_FAILURE
, errno
, _("write error"));
1203 /* If nothing was read, sleep and/or check for dead writers. */
1209 /* Once the writer is dead, read the files once more to
1210 avoid a race condition. */
1211 writer_is_dead
= (pid
!= 0
1212 && kill (pid
, 0) != 0
1213 /* Handle the case in which you cannot send a
1214 signal to the writer, so kill fails and sets
1218 if (!writer_is_dead
&& xnanosleep (sleep_interval
))
1219 error (EXIT_FAILURE
, errno
, _("cannot read realtime clock"));
1227 /* Return true if any of the N_FILES files in F is remote, i.e., has
1228 an open file descriptor and is on a network file system. */
1231 any_remote_file (const struct File_spec
*f
, size_t n_files
)
1235 for (i
= 0; i
< n_files
; i
++)
1236 if (0 <= f
[i
].fd
&& f
[i
].remote
)
1241 /* Return true if any of the N_FILES files in F represents
1242 stdin and is tailable. */
1245 tailable_stdin (const struct File_spec
*f
, size_t n_files
)
1249 for (i
= 0; i
< n_files
; i
++)
1250 if (!f
[i
].ignore
&& STREQ (f
[i
].name
, "-"))
1256 wd_hasher (const void *entry
, size_t tabsize
)
1258 const struct File_spec
*spec
= entry
;
1259 return spec
->wd
% tabsize
;
1263 wd_comparator (const void *e1
, const void *e2
)
1265 const struct File_spec
*spec1
= e1
;
1266 const struct File_spec
*spec2
= e2
;
1267 return spec1
->wd
== spec2
->wd
;
1270 /* Helper function used by 'tail_forever_inotify'. */
1272 check_fspec (struct File_spec
*fspec
, int wd
, int *prev_wd
)
1275 char const *name
= pretty_name (fspec
);
1277 if (fstat (fspec
->fd
, &stats
) != 0)
1279 close_fd (fspec
->fd
, name
);
1281 fspec
->errnum
= errno
;
1285 if (S_ISREG (fspec
->mode
) && stats
.st_size
< fspec
->size
)
1287 error (0, 0, _("%s: file truncated"), name
);
1289 xlseek (fspec
->fd
, stats
.st_size
, SEEK_SET
, name
);
1290 fspec
->size
= stats
.st_size
;
1292 else if (S_ISREG (fspec
->mode
) && stats
.st_size
== fspec
->size
1293 && timespec_cmp (fspec
->mtime
, get_stat_mtime (&stats
)) == 0)
1299 write_header (name
);
1303 uintmax_t bytes_read
= dump_remainder (name
, fspec
->fd
, COPY_TO_EOF
);
1304 fspec
->size
+= bytes_read
;
1306 if (fflush (stdout
) != 0)
1307 error (EXIT_FAILURE
, errno
, _("write error"));
1310 /* Attempt to tail N_FILES files forever, or until killed.
1311 Check modifications using the inotify events system.
1312 Return false on error, or true to revert to polling. */
1314 tail_forever_inotify (int wd
, struct File_spec
*f
, size_t n_files
,
1315 double sleep_interval
)
1317 unsigned int max_realloc
= 3;
1319 /* Map an inotify watch descriptor to the name of the file it's watching. */
1320 Hash_table
*wd_to_name
;
1322 bool found_watchable_file
= false;
1323 bool found_unwatchable_dir
= false;
1324 bool no_inotify_resources
= false;
1325 bool writer_is_dead
= false;
1329 size_t evbuf_off
= 0;
1332 wd_to_name
= hash_initialize (n_files
, NULL
, wd_hasher
, wd_comparator
, NULL
);
1336 /* Add an inotify watch for each watched file. If -F is specified then watch
1337 its parent directory too, in this way when they re-appear we can add them
1338 again to the watch list. */
1340 for (i
= 0; i
< n_files
; i
++)
1344 size_t fnlen
= strlen (f
[i
].name
);
1350 if (follow_mode
== Follow_name
)
1352 size_t dirlen
= dir_len (f
[i
].name
);
1353 char prev
= f
[i
].name
[dirlen
];
1354 f
[i
].basename_start
= last_component (f
[i
].name
) - f
[i
].name
;
1356 f
[i
].name
[dirlen
] = '\0';
1358 /* It's fine to add the same directory more than once.
1359 In that case the same watch descriptor is returned. */
1360 f
[i
].parent_wd
= inotify_add_watch (wd
, dirlen
? f
[i
].name
: ".",
1361 (IN_CREATE
| IN_MOVED_TO
1364 f
[i
].name
[dirlen
] = prev
;
1366 if (f
[i
].parent_wd
< 0)
1368 if (errno
!= ENOSPC
) /* suppress confusing error. */
1369 error (0, errno
, _("cannot watch parent directory of %s"),
1372 error (0, 0, _("inotify resources exhausted"));
1373 found_unwatchable_dir
= true;
1374 /* We revert to polling below. Note invalid uses
1375 of the inotify API will still be diagnosed. */
1380 f
[i
].wd
= inotify_add_watch (wd
, f
[i
].name
, inotify_wd_mask
);
1384 if (errno
== ENOSPC
)
1386 no_inotify_resources
= true;
1387 error (0, 0, _("inotify resources exhausted"));
1389 else if (errno
!= f
[i
].errnum
)
1390 error (0, errno
, _("cannot watch %s"), quote (f
[i
].name
));
1394 if (hash_insert (wd_to_name
, &(f
[i
])) == NULL
)
1397 found_watchable_file
= true;
1401 /* Linux kernel 2.6.24 at least has a bug where eventually, ENOSPC is always
1402 returned by inotify_add_watch. In any case we should revert to polling
1403 when there are no inotify resources. Also a specified directory may not
1404 be currently present or accessible, so revert to polling. */
1405 if (no_inotify_resources
|| found_unwatchable_dir
)
1407 /* FIXME: release hash and inotify resources allocated above. */
1411 if (follow_mode
== Follow_descriptor
&& !found_watchable_file
)
1414 prev_wd
= f
[n_files
- 1].wd
;
1416 /* Check files again. New data can be available since last time we checked
1417 and before they are watched by inotify. */
1418 for (i
= 0; i
< n_files
; i
++)
1421 check_fspec (&f
[i
], f
[i
].wd
, &prev_wd
);
1424 evlen
+= sizeof (struct inotify_event
) + 1;
1425 evbuf
= xmalloc (evlen
);
1427 /* Wait for inotify events and handle them. Events on directories
1428 ensure that watched files can be re-added when following by name.
1429 This loop blocks on the 'safe_read' call until a new event is notified.
1430 But when --pid=P is specified, tail usually waits via the select. */
1433 struct File_spec
*fspec
;
1434 struct inotify_event
*ev
;
1436 /* When following by name without --retry, and the last file has
1437 been unlinked or renamed-away, diagnose it and return. */
1438 if (follow_mode
== Follow_name
1439 && ! reopen_inaccessible_files
1440 && hash_get_n_entries (wd_to_name
) == 0)
1442 error (0, 0, _("no files remaining"));
1446 /* When watching a PID, ensure that a read from WD will not block
1451 exit (EXIT_SUCCESS
);
1453 writer_is_dead
= (kill (pid
, 0) != 0 && errno
!= EPERM
);
1455 struct timeval delay
; /* how long to wait for file changes. */
1457 delay
.tv_sec
= delay
.tv_usec
= 0;
1460 delay
.tv_sec
= (time_t) sleep_interval
;
1461 delay
.tv_usec
= 1000000 * (sleep_interval
- delay
.tv_sec
);
1468 int file_change
= select (wd
+ 1, &rfd
, NULL
, NULL
, &delay
);
1470 if (file_change
== 0)
1472 else if (file_change
== -1)
1473 error (EXIT_FAILURE
, errno
, _("error monitoring inotify event"));
1476 if (len
<= evbuf_off
)
1478 len
= safe_read (wd
, evbuf
, evlen
);
1481 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1483 if ((len
== 0 || (len
== SAFE_READ_ERROR
&& errno
== EINVAL
))
1488 evbuf
= xrealloc (evbuf
, evlen
);
1492 if (len
== 0 || len
== SAFE_READ_ERROR
)
1493 error (EXIT_FAILURE
, errno
, _("error reading inotify event"));
1496 ev
= (struct inotify_event
*) (evbuf
+ evbuf_off
);
1497 evbuf_off
+= sizeof (*ev
) + ev
->len
;
1499 if (ev
->len
) /* event on ev->name in watched directory */
1502 for (j
= 0; j
< n_files
; j
++)
1504 /* With N=hundreds of frequently-changing files, this O(N^2)
1505 process might be a problem. FIXME: use a hash table? */
1506 if (f
[j
].parent_wd
== ev
->wd
1507 && STREQ (ev
->name
, f
[j
].name
+ f
[j
].basename_start
))
1511 /* It is not a watched file. */
1515 /* It's fine to add the same file more than once. */
1516 int new_wd
= inotify_add_watch (wd
, f
[j
].name
, inotify_wd_mask
);
1519 error (0, errno
, _("cannot watch %s"), quote (f
[j
].name
));
1525 /* Remove 'fspec' and re-add it using 'new_fd' as its key. */
1526 hash_delete (wd_to_name
, fspec
);
1529 /* If the file was moved then inotify will use the source file wd for
1530 the destination file. Make sure the key is not present in the
1532 struct File_spec
*prev
= hash_delete (wd_to_name
, fspec
);
1533 if (prev
&& prev
!= fspec
)
1535 if (follow_mode
== Follow_name
)
1536 recheck (prev
, false);
1538 close_fd (prev
->fd
, pretty_name (prev
));
1541 if (hash_insert (wd_to_name
, fspec
) == NULL
)
1544 if (follow_mode
== Follow_name
)
1545 recheck (fspec
, false);
1549 struct File_spec key
;
1551 fspec
= hash_lookup (wd_to_name
, &key
);
1557 if (ev
->mask
& (IN_ATTRIB
| IN_DELETE_SELF
| IN_MOVE_SELF
))
1559 /* For IN_DELETE_SELF, we always want to remove the watch.
1560 However, for IN_MOVE_SELF (the file we're watching has
1561 been clobbered via a rename), when tailing by NAME, we
1562 must continue to watch the file. It's only when following
1563 by file descriptor that we must remove the watch. */
1564 if ((ev
->mask
& IN_DELETE_SELF
)
1565 || ((ev
->mask
& IN_MOVE_SELF
)
1566 && follow_mode
== Follow_descriptor
))
1568 inotify_rm_watch (wd
, fspec
->wd
);
1569 hash_delete (wd_to_name
, fspec
);
1571 if (follow_mode
== Follow_name
)
1572 recheck (fspec
, false);
1576 check_fspec (fspec
, ev
->wd
, &prev_wd
);
1581 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1582 Return true if successful. */
1585 tail_bytes (const char *pretty_filename
, int fd
, uintmax_t n_bytes
,
1586 uintmax_t *read_pos
)
1590 if (fstat (fd
, &stats
))
1592 error (0, errno
, _("cannot fstat %s"), quote (pretty_filename
));
1598 if ( ! presume_input_pipe
1599 && S_ISREG (stats
.st_mode
) && n_bytes
<= OFF_T_MAX
)
1601 xlseek (fd
, n_bytes
, SEEK_CUR
, pretty_filename
);
1602 *read_pos
+= n_bytes
;
1606 int t
= start_bytes (pretty_filename
, fd
, n_bytes
, read_pos
);
1610 *read_pos
+= dump_remainder (pretty_filename
, fd
, COPY_TO_EOF
);
1614 if ( ! presume_input_pipe
1615 && S_ISREG (stats
.st_mode
) && n_bytes
<= OFF_T_MAX
)
1617 off_t current_pos
= xlseek (fd
, 0, SEEK_CUR
, pretty_filename
);
1618 off_t end_pos
= xlseek (fd
, 0, SEEK_END
, pretty_filename
);
1619 off_t diff
= end_pos
- current_pos
;
1620 /* Be careful here. The current position may actually be
1621 beyond the end of the file. */
1622 off_t bytes_remaining
= diff
< 0 ? 0 : diff
;
1625 if (bytes_remaining
<= nb
)
1627 /* From the current position to end of file, there are no
1628 more bytes than have been requested. So reposition the
1629 file pointer to the incoming current position and print
1630 everything after that. */
1631 *read_pos
= xlseek (fd
, current_pos
, SEEK_SET
, pretty_filename
);
1635 /* There are more bytes remaining than were requested.
1637 *read_pos
= xlseek (fd
, -nb
, SEEK_END
, pretty_filename
);
1639 *read_pos
+= dump_remainder (pretty_filename
, fd
, n_bytes
);
1642 return pipe_bytes (pretty_filename
, fd
, n_bytes
, read_pos
);
1647 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1648 Return true if successful. */
1651 tail_lines (const char *pretty_filename
, int fd
, uintmax_t n_lines
,
1652 uintmax_t *read_pos
)
1656 if (fstat (fd
, &stats
))
1658 error (0, errno
, _("cannot fstat %s"), quote (pretty_filename
));
1664 int t
= start_lines (pretty_filename
, fd
, n_lines
, read_pos
);
1667 *read_pos
+= dump_remainder (pretty_filename
, fd
, COPY_TO_EOF
);
1671 off_t start_pos
= -1;
1674 /* Use file_lines only if FD refers to a regular file for
1675 which lseek (... SEEK_END) works. */
1676 if ( ! presume_input_pipe
1677 && S_ISREG (stats
.st_mode
)
1678 && (start_pos
= lseek (fd
, 0, SEEK_CUR
)) != -1
1679 && start_pos
< (end_pos
= lseek (fd
, 0, SEEK_END
)))
1681 *read_pos
= end_pos
;
1683 && ! file_lines (pretty_filename
, fd
, n_lines
,
1684 start_pos
, end_pos
, read_pos
))
1689 /* Under very unlikely circumstances, it is possible to reach
1690 this point after positioning the file pointer to end of file
1691 via the 'lseek (...SEEK_END)' above. In that case, reposition
1692 the file pointer back to start_pos before calling pipe_lines. */
1693 if (start_pos
!= -1)
1694 xlseek (fd
, start_pos
, SEEK_SET
, pretty_filename
);
1696 return pipe_lines (pretty_filename
, fd
, n_lines
, read_pos
);
1702 /* Display the last N_UNITS units of file FILENAME, open for reading
1703 via FD. Set *READ_POS to the position of the input stream pointer.
1704 *READ_POS is usually the number of bytes read and corresponds to an
1705 offset from the beginning of a file. However, it may be larger than
1706 OFF_T_MAX (as for an input pipe), and may also be larger than the
1707 number of bytes read (when an input pointer is initially not at
1708 beginning of file), and may be far greater than the number of bytes
1709 actually read for an input file that is seekable.
1710 Return true if successful. */
1713 tail (const char *filename
, int fd
, uintmax_t n_units
,
1714 uintmax_t *read_pos
)
1718 return tail_lines (filename
, fd
, n_units
, read_pos
);
1720 return tail_bytes (filename
, fd
, n_units
, read_pos
);
1723 /* Display the last N_UNITS units of the file described by F.
1724 Return true if successful. */
1727 tail_file (struct File_spec
*f
, uintmax_t n_units
)
1732 bool is_stdin
= (STREQ (f
->name
, "-"));
1736 have_read_stdin
= true;
1738 if (O_BINARY
&& ! isatty (STDIN_FILENO
))
1739 xfreopen (NULL
, "rb", stdin
);
1742 fd
= open (f
->name
, O_RDONLY
| O_BINARY
);
1744 f
->tailable
= !(reopen_inaccessible_files
&& fd
== -1);
1756 error (0, errno
, _("cannot open %s for reading"),
1757 quote (pretty_name (f
)));
1765 write_header (pretty_name (f
));
1766 ok
= tail (pretty_name (f
), fd
, n_units
, &read_pos
);
1771 #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
1772 /* Before the tail function provided 'read_pos', there was
1773 a race condition described in the URL below. This sleep
1774 call made the window big enough to exercise the problem. */
1778 if (fstat (fd
, &stats
) < 0)
1782 error (0, errno
, _("error reading %s"), quote (pretty_name (f
)));
1784 else if (!IS_TAILABLE_FILE_TYPE (stats
.st_mode
))
1786 error (0, 0, _("%s: cannot follow end of this type of file;\
1787 giving up on this name"),
1796 close_fd (fd
, pretty_name (f
));
1801 /* Note: we must use read_pos here, not stats.st_size,
1802 to avoid a race condition described by Ken Raeburn:
1803 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1804 record_open_fd (f
, fd
, read_pos
, &stats
, (is_stdin
? -1 : 1));
1805 f
->remote
= fremote (fd
, pretty_name (f
));
1810 if (!is_stdin
&& close (fd
))
1812 error (0, errno
, _("error reading %s"), quote (pretty_name (f
)));
1821 /* If obsolete usage is allowed, and the command line arguments are of
1822 the obsolete form and the option string is well-formed, set
1823 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1824 return true. If the command line arguments are obviously incorrect
1825 (e.g., because obsolete usage is not allowed and the arguments are
1826 incorrect for non-obsolete usage), report an error and exit.
1827 Otherwise, return false and don't modify any parameter or global
1831 parse_obsolete_option (int argc
, char * const *argv
, uintmax_t *n_units
)
1834 const char *n_string
;
1835 const char *n_string_end
;
1836 bool obsolete_usage
;
1837 int default_count
= DEFAULT_N_LINES
;
1839 bool t_count_lines
= true;
1840 bool t_forever
= false;
1842 /* With the obsolete form, there is one option string and at most
1843 one file argument. Watch out for "-" and "--", though. */
1845 || (argc
== 3 && ! (argv
[2][0] == '-' && argv
[2][1]))
1846 || (3 <= argc
&& argc
<= 4 && STREQ (argv
[2], "--"))))
1849 obsolete_usage
= (posix2_version () < 200112);
1858 /* Leading "+" is a file name in the non-obsolete form. */
1859 if (!obsolete_usage
)
1862 t_from_start
= true;
1866 /* In the non-obsolete form, "-" is standard input and "-c"
1867 requires an option-argument. The obsolete multidigit options
1868 are supported as a GNU extension even when conforming to
1869 POSIX 1003.1-2001, so don't complain about them. */
1870 if (!obsolete_usage
&& !p
[p
[0] == 'c'])
1873 t_from_start
= false;
1878 while (ISDIGIT (*p
))
1884 case 'b': default_count
*= 512; /* Fall through. */
1885 case 'c': t_count_lines
= false; /* Fall through. */
1886 case 'l': p
++; break;
1898 if (n_string
== n_string_end
)
1899 *n_units
= default_count
;
1900 else if ((xstrtoumax (n_string
, NULL
, 10, n_units
, "b")
1901 & ~LONGINT_INVALID_SUFFIX_CHAR
)
1903 error (EXIT_FAILURE
, 0, _("number in %s is too large"), quote (argv
[1]));
1906 from_start
= t_from_start
;
1907 count_lines
= t_count_lines
;
1908 forever
= t_forever
;
1914 parse_options (int argc
, char **argv
,
1915 uintmax_t *n_units
, enum header_mode
*header_mode
,
1916 double *sleep_interval
)
1920 while ((c
= getopt_long (argc
, argv
, "c:n:fFqs:v0123456789",
1921 long_options
, NULL
))
1928 follow_mode
= Follow_name
;
1929 reopen_inaccessible_files
= true;
1934 count_lines
= (c
== 'n');
1937 else if (*optarg
== '-')
1942 s_err
= xstrtoumax (optarg
, NULL
, 10, n_units
, "bkKmMGTPEZY0");
1943 if (s_err
!= LONGINT_OK
)
1945 error (EXIT_FAILURE
, 0, "%s: %s", optarg
,
1947 ? _("invalid number of lines")
1948 : _("invalid number of bytes")));
1954 case LONG_FOLLOW_OPTION
:
1957 follow_mode
= DEFAULT_FOLLOW_MODE
;
1959 follow_mode
= XARGMATCH ("--follow", optarg
,
1960 follow_mode_string
, follow_mode_map
);
1964 reopen_inaccessible_files
= true;
1967 case MAX_UNCHANGED_STATS_OPTION
:
1968 /* --max-unchanged-stats=N */
1969 if (xstrtoumax (optarg
, NULL
, 10,
1970 &max_n_unchanged_stats_between_opens
,
1974 error (EXIT_FAILURE
, 0,
1975 _("%s: invalid maximum number of unchanged stats between opens"),
1980 case DISABLE_INOTIFY_OPTION
:
1981 disable_inotify
= true;
1987 unsigned long int tmp_ulong
;
1988 s_err
= xstrtoul (optarg
, NULL
, 10, &tmp_ulong
, "");
1989 if (s_err
!= LONGINT_OK
|| tmp_ulong
> PID_T_MAX
)
1991 error (EXIT_FAILURE
, 0, _("%s: invalid PID"), optarg
);
1997 case PRESUME_INPUT_PIPE_OPTION
:
1998 presume_input_pipe
= true;
2002 *header_mode
= never
;
2008 if (! (xstrtod (optarg
, NULL
, &s
, c_strtod
) && 0 <= s
))
2009 error (EXIT_FAILURE
, 0,
2010 _("%s: invalid number of seconds"), optarg
);
2011 *sleep_interval
= s
;
2016 *header_mode
= always
;
2019 case_GETOPT_HELP_CHAR
;
2021 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
2023 case '0': case '1': case '2': case '3': case '4':
2024 case '5': case '6': case '7': case '8': case '9':
2025 error (EXIT_FAILURE
, 0,
2026 _("option used in invalid context -- %c"), c
);
2029 usage (EXIT_FAILURE
);
2033 if (reopen_inaccessible_files
&& follow_mode
!= Follow_name
)
2034 error (0, 0, _("warning: --retry is useful mainly when following by name"));
2036 if (pid
&& !forever
)
2038 _("warning: PID ignored; --pid=PID is useful only when following"));
2039 else if (pid
&& kill (pid
, 0) != 0 && errno
== ENOSYS
)
2041 error (0, 0, _("warning: --pid=PID is not supported on this system"));
2046 /* Mark as '.ignore'd each member of F that corresponds to a
2047 pipe or fifo, and return the number of non-ignored members. */
2049 ignore_fifo_and_pipe (struct File_spec
*f
, size_t n_files
)
2051 /* When there is no FILE operand and stdin is a pipe or FIFO
2052 POSIX requires that tail ignore the -f option.
2053 Since we allow multiple FILE operands, we extend that to say: with -f,
2054 ignore any "-" operand that corresponds to a pipe or FIFO. */
2055 size_t n_viable
= 0;
2058 for (i
= 0; i
< n_files
; i
++)
2060 bool is_a_fifo_or_pipe
=
2061 (STREQ (f
[i
].name
, "-")
2064 && (S_ISFIFO (f
[i
].mode
)
2065 || (HAVE_FIFO_PIPES
!= 1 && isapipe (f
[i
].fd
))));
2066 if (is_a_fifo_or_pipe
)
2076 main (int argc
, char **argv
)
2078 enum header_mode header_mode
= multiple_files
;
2080 /* If from_start, the number of items to skip before printing; otherwise,
2081 the number of items at the end of the file to print. Although the type
2082 is signed, the value is never negative. */
2083 uintmax_t n_units
= DEFAULT_N_LINES
;
2086 struct File_spec
*F
;
2088 bool obsolete_option
;
2090 /* The number of seconds to sleep between iterations.
2091 During one iteration, every file name or descriptor is checked to
2092 see if it has changed. */
2093 double sleep_interval
= 1.0;
2095 initialize_main (&argc
, &argv
);
2096 set_program_name (argv
[0]);
2097 setlocale (LC_ALL
, "");
2098 bindtextdomain (PACKAGE
, LOCALEDIR
);
2099 textdomain (PACKAGE
);
2101 atexit (close_stdout
);
2103 have_read_stdin
= false;
2106 forever
= from_start
= print_headers
= false;
2107 obsolete_option
= parse_obsolete_option (argc
, argv
, &n_units
);
2108 argc
-= obsolete_option
;
2109 argv
+= obsolete_option
;
2110 parse_options (argc
, argv
, &n_units
, &header_mode
, &sleep_interval
);
2112 /* To start printing with item N_UNITS from the start of the file, skip
2113 N_UNITS - 1 items. 'tail -n +0' is actually meaningless, but for Unix
2114 compatibility it's treated the same as 'tail -n +1'. */
2123 n_files
= argc
- optind
;
2124 file
= argv
+ optind
;
2128 static char *dummy_stdin
= (char *) "-";
2130 file
= &dummy_stdin
;
2134 bool found_hyphen
= false;
2136 for (i
= 0; i
< n_files
; i
++)
2137 if (STREQ (file
[i
], "-"))
2138 found_hyphen
= true;
2140 /* When following by name, there must be a name. */
2141 if (found_hyphen
&& follow_mode
== Follow_name
)
2142 error (EXIT_FAILURE
, 0, _("cannot follow %s by name"), quote ("-"));
2144 /* When following forever, warn if any file is '-'.
2145 This is only a warning, since tail's output (before a failing seek,
2146 and that from any non-stdin files) might still be useful. */
2147 if (forever
&& found_hyphen
&& isatty (STDIN_FILENO
))
2148 error (0, 0, _("warning: following standard input"
2149 " indefinitely is ineffective"));
2152 F
= xnmalloc (n_files
, sizeof *F
);
2153 for (i
= 0; i
< n_files
; i
++)
2154 F
[i
].name
= file
[i
];
2156 if (header_mode
== always
2157 || (header_mode
== multiple_files
&& n_files
> 1))
2158 print_headers
= true;
2160 if (O_BINARY
&& ! isatty (STDOUT_FILENO
))
2161 xfreopen (NULL
, "wb", stdout
);
2163 for (i
= 0; i
< n_files
; i
++)
2164 ok
&= tail_file (&F
[i
], n_units
);
2166 if (forever
&& ignore_fifo_and_pipe (F
, n_files
))
2169 /* tailable_stdin() checks if the user specifies stdin via "-",
2170 or implicitly by providing no arguments. If so, we won't use inotify.
2171 Technically, on systems with a working /dev/stdin, we *could*,
2172 but would it be worth it? Verifying that it's a real device
2173 and hooked up to stdin is not trivial, while reverting to
2174 non-inotify-based tail_forever is easy and portable.
2176 any_remote_file() checks if the user has specified any
2177 files that reside on remote file systems. inotify is not used
2178 in this case because it would miss any updates to the file
2179 that were not initiated from the local system.
2181 FIXME: inotify doesn't give any notification when a new
2182 (remote) file or directory is mounted on top a watched file.
2183 When follow_mode == Follow_name we would ideally like to detect that.
2184 Note if there is a change to the original file then we'll
2185 recheck it and follow the new file, or ignore it if the
2186 file has changed to being remote.
2188 FIXME: when using inotify, and a directory for a watched file
2189 is recreated, then we don't recheck any new file when
2190 follow_mode == Follow_name */
2191 if (!disable_inotify
&& (tailable_stdin (F
, n_files
)
2192 || any_remote_file (F
, n_files
)))
2193 disable_inotify
= true;
2195 if (!disable_inotify
)
2197 int wd
= inotify_init ();
2200 /* Flush any output from tail_file, now, since
2201 tail_forever_inotify flushes only after writing,
2202 not before reading. */
2203 if (fflush (stdout
) != 0)
2204 error (EXIT_FAILURE
, errno
, _("write error"));
2206 if (!tail_forever_inotify (wd
, F
, n_files
, sleep_interval
))
2207 exit (EXIT_FAILURE
);
2209 error (0, errno
, _("inotify cannot be used, reverting to polling"));
2212 disable_inotify
= true;
2213 tail_forever (F
, n_files
, sleep_interval
);
2216 if (have_read_stdin
&& close (STDIN_FILENO
) < 0)
2217 error (EXIT_FAILURE
, errno
, "-");
2218 exit (ok
? EXIT_SUCCESS
: EXIT_FAILURE
);