tests: ensure touch honors trailing slash
[coreutils/ericb.git] / src / tail.c
blob97aa8d4964b3dfc82fc9953a8836f80301a897e0
1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989, 90, 91, 1995-2006, 2008-2009 Free Software
3 Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. */
18 /* Can display any amount of data, unlike the Unix version, which uses
19 a fixed size buffer and therefore can only deliver a limited number
20 of lines.
22 Original version by Paul Rubin <phr@ocf.berkeley.edu>.
23 Extensions by David MacKenzie <djm@gnu.ai.mit.edu>.
24 tail -f for multiple files by Ian Lance Taylor <ian@airs.com>.
25 inotify back-end by Giuseppe Scrivano <gscrivano@gnu.org>. */
27 #include <config.h>
29 #include <stdio.h>
30 #include <assert.h>
31 #include <getopt.h>
32 #include <sys/types.h>
33 #include <signal.h>
35 #include "system.h"
36 #include "argmatch.h"
37 #include "c-strtod.h"
38 #include "error.h"
39 #include "fcntl--.h"
40 #include "isapipe.h"
41 #include "posixver.h"
42 #include "quote.h"
43 #include "safe-read.h"
44 #include "stat-time.h"
45 #include "xfreopen.h"
46 #include "xnanosleep.h"
47 #include "xstrtol.h"
48 #include "xstrtod.h"
50 #if HAVE_INOTIFY
51 # include "hash.h"
52 # include <sys/inotify.h>
53 /* `select' is used by tail_forever_inotify. */
54 # include <sys/select.h>
55 #endif
57 /* The official name of this program (e.g., no `g' prefix). */
58 #define PROGRAM_NAME "tail"
60 #define AUTHORS \
61 proper_name ("Paul Rubin"), \
62 proper_name ("David MacKenzie"), \
63 proper_name ("Ian Lance Taylor"), \
64 proper_name ("Jim Meyering")
66 /* Number of items to tail. */
67 #define DEFAULT_N_LINES 10
69 /* Special values for dump_remainder's N_BYTES parameter. */
70 #define COPY_TO_EOF UINTMAX_MAX
71 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
73 /* FIXME: make Follow_name the default? */
74 #define DEFAULT_FOLLOW_MODE Follow_descriptor
76 enum Follow_mode
78 /* Follow the name of each file: if the file is renamed, try to reopen
79 that name and track the end of the new file if/when it's recreated.
80 This is useful for tracking logs that are occasionally rotated. */
81 Follow_name = 1,
83 /* Follow each descriptor obtained upon opening a file.
84 That means we'll continue to follow the end of a file even after
85 it has been renamed or unlinked. */
86 Follow_descriptor = 2
89 /* The types of files for which tail works. */
90 #define IS_TAILABLE_FILE_TYPE(Mode) \
91 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
93 static char const *const follow_mode_string[] =
95 "descriptor", "name", NULL
98 static enum Follow_mode const follow_mode_map[] =
100 Follow_descriptor, Follow_name,
103 struct File_spec
105 /* The actual file name, or "-" for stdin. */
106 char *name;
108 /* File descriptor on which the file is open; -1 if it's not open. */
109 int fd;
111 /* Attributes of the file the last time we checked. */
112 off_t size;
113 struct timespec mtime;
114 dev_t dev;
115 ino_t ino;
116 mode_t mode;
118 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
119 int blocking;
121 /* The specified name initially referred to a directory or some other
122 type for which tail isn't meaningful. Unlike for a permission problem
123 (tailable, below) once this is set, the name is not checked ever again. */
124 bool ignore;
126 /* See description of DEFAULT_MAX_N_... below. */
127 uintmax_t n_unchanged_stats;
129 /* A file is tailable if it exists, is readable, and is of type
130 IS_TAILABLE_FILE_TYPE. */
131 bool tailable;
133 /* The value of errno seen last time we checked this file. */
134 int errnum;
136 #if HAVE_INOTIFY
137 /* The watch descriptor used by inotify. */
138 int wd;
140 /* The parent directory watch descriptor. It is used only
141 * when Follow_name is used. */
142 int parent_wd;
144 /* Offset in NAME of the basename part. */
145 size_t basename_start;
146 #endif
149 #if HAVE_INOTIFY
150 /* The events mask used with inotify on files. This mask is not used on
151 directories. */
152 const uint32_t inotify_wd_mask = (IN_MODIFY | IN_ATTRIB | IN_DELETE_SELF
153 | IN_MOVE_SELF);
154 #endif
156 /* Keep trying to open a file even if it is inaccessible when tail starts
157 or if it becomes inaccessible later -- useful only with -f. */
158 static bool reopen_inaccessible_files;
160 /* If true, interpret the numeric argument as the number of lines.
161 Otherwise, interpret it as the number of bytes. */
162 static bool count_lines;
164 /* Whether we follow the name of each file or the file descriptor
165 that is initially associated with each name. */
166 static enum Follow_mode follow_mode = Follow_descriptor;
168 /* If true, read from the ends of all specified files until killed. */
169 static bool forever;
171 /* If true, count from start of file instead of end. */
172 static bool from_start;
174 /* If true, print filename headers. */
175 static bool print_headers;
177 /* When to print the filename banners. */
178 enum header_mode
180 multiple_files, always, never
183 /* When tailing a file by name, if there have been this many consecutive
184 iterations for which the file has not changed, then open/fstat
185 the file to determine if that file name is still associated with the
186 same device/inode-number pair as before. This option is meaningful only
187 when following by name. --max-unchanged-stats=N */
188 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
189 static uintmax_t max_n_unchanged_stats_between_opens =
190 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
192 /* The process ID of the process (presumably on the current host)
193 that is writing to all followed files. */
194 static pid_t pid;
196 /* True if we have ever read standard input. */
197 static bool have_read_stdin;
199 /* If nonzero, skip the is-regular-file test used to determine whether
200 to use the lseek optimization. Instead, use the more general (and
201 more expensive) code unconditionally. Intended solely for testing. */
202 static bool presume_input_pipe;
204 /* If nonzero then don't use inotify even if available.
205 Intended solely for testing. */
206 static bool disable_inotify;
208 /* For long options that have no equivalent short option, use a
209 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
210 enum
212 RETRY_OPTION = CHAR_MAX + 1,
213 MAX_UNCHANGED_STATS_OPTION,
214 PID_OPTION,
215 PRESUME_INPUT_PIPE_OPTION,
216 LONG_FOLLOW_OPTION,
217 DISABLE_INOTIFY_OPTION
220 static struct option const long_options[] =
222 {"bytes", required_argument, NULL, 'c'},
223 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
224 {"lines", required_argument, NULL, 'n'},
225 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
226 {"-disable-inotify", no_argument, NULL,
227 DISABLE_INOTIFY_OPTION}, /* do not document */
228 {"pid", required_argument, NULL, PID_OPTION},
229 {"-presume-input-pipe", no_argument, NULL,
230 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
231 {"quiet", no_argument, NULL, 'q'},
232 {"retry", no_argument, NULL, RETRY_OPTION},
233 {"silent", no_argument, NULL, 'q'},
234 {"sleep-interval", required_argument, NULL, 's'},
235 {"verbose", no_argument, NULL, 'v'},
236 {GETOPT_HELP_OPTION_DECL},
237 {GETOPT_VERSION_OPTION_DECL},
238 {NULL, 0, NULL, 0}
241 void
242 usage (int status)
244 if (status != EXIT_SUCCESS)
245 fprintf (stderr, _("Try `%s --help' for more information.\n"),
246 program_name);
247 else
249 printf (_("\
250 Usage: %s [OPTION]... [FILE]...\n\
252 program_name);
253 printf (_("\
254 Print the last %d lines of each FILE to standard output.\n\
255 With more than one FILE, precede each with a header giving the file name.\n\
256 With no FILE, or when FILE is -, read standard input.\n\
258 "), DEFAULT_N_LINES);
259 fputs (_("\
260 Mandatory arguments to long options are mandatory for short options too.\n\
261 "), stdout);
262 fputs (_("\
263 -c, --bytes=K output the last K bytes; alternatively, use -c +K\n\
264 to output bytes starting with the Kth of each file\n\
265 "), stdout);
266 fputs (_("\
267 -f, --follow[={name|descriptor}]\n\
268 output appended data as the file grows;\n\
269 -f, --follow, and --follow=descriptor are\n\
270 equivalent\n\
271 -F same as --follow=name --retry\n\
272 "), stdout);
273 printf (_("\
274 -n, --lines=K output the last K lines, instead of the last %d;\n\
275 or use -n +K to output lines starting with the Kth\n\
276 --max-unchanged-stats=N\n\
277 with --follow=name, reopen a FILE which has not\n\
278 changed size after N (default %d) iterations\n\
279 to see if it has been unlinked or renamed\n\
280 (this is the usual case of rotated log files)\n\
282 DEFAULT_N_LINES,
283 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
285 fputs (_("\
286 --pid=PID with -f, terminate after process ID, PID dies\n\
287 -q, --quiet, --silent never output headers giving file names\n\
288 --retry keep trying to open a file even when it is or\n\
289 becomes inaccessible; useful when following by\n\
290 name, i.e., with --follow=name\n\
291 "), stdout);
292 fputs (_("\
293 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
294 (default 1.0) between iterations\n\
295 -v, --verbose always output headers giving file names\n\
296 "), stdout);
297 fputs (HELP_OPTION_DESCRIPTION, stdout);
298 fputs (VERSION_OPTION_DESCRIPTION, stdout);
299 fputs (_("\
301 If the first character of K (the number of bytes or lines) is a `+',\n\
302 print beginning with the Kth item from the start of each file, otherwise,\n\
303 print the last K items in the file. K may have a multiplier suffix:\n\
304 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
305 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
307 "), stdout);
308 fputs (_("\
309 With --follow (-f), tail defaults to following the file descriptor, which\n\
310 means that even if a tail'ed file is renamed, tail will continue to track\n\
311 its end. \
312 "), stdout);
313 fputs (_("\
314 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 by reopening it periodically to see if it has been removed and\n\
318 recreated by some other program.\n\
319 "), stdout);
320 emit_ancillary_info ();
322 exit (status);
325 static bool
326 valid_file_spec (struct File_spec const *f)
328 /* Exactly one of the following subexpressions must be true. */
329 return ((f->fd == -1) ^ (f->errnum == 0));
332 static char const *
333 pretty_name (struct File_spec const *f)
335 return (STREQ (f->name, "-") ? _("standard input") : f->name);
338 static void
339 xwrite_stdout (char const *buffer, size_t n_bytes)
341 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
342 error (EXIT_FAILURE, errno, _("write error"));
345 /* Record a file F with descriptor FD, size SIZE, status ST, and
346 blocking status BLOCKING. */
348 static void
349 record_open_fd (struct File_spec *f, int fd,
350 off_t size, struct stat const *st,
351 int blocking)
353 f->fd = fd;
354 f->size = size;
355 f->mtime = get_stat_mtime (st);
356 f->dev = st->st_dev;
357 f->ino = st->st_ino;
358 f->mode = st->st_mode;
359 f->blocking = blocking;
360 f->n_unchanged_stats = 0;
361 f->ignore = false;
364 /* Close the file with descriptor FD and name FILENAME. */
366 static void
367 close_fd (int fd, const char *filename)
369 if (fd != -1 && fd != STDIN_FILENO && close (fd))
371 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
375 static void
376 write_header (const char *pretty_filename)
378 static bool first_file = true;
380 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
381 first_file = false;
384 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
385 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
386 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
387 Return the number of bytes read from the file. */
389 static uintmax_t
390 dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
392 uintmax_t n_written;
393 uintmax_t n_remaining = n_bytes;
395 n_written = 0;
396 while (1)
398 char buffer[BUFSIZ];
399 size_t n = MIN (n_remaining, BUFSIZ);
400 size_t bytes_read = safe_read (fd, buffer, n);
401 if (bytes_read == SAFE_READ_ERROR)
403 if (errno != EAGAIN)
404 error (EXIT_FAILURE, errno, _("error reading %s"),
405 quote (pretty_filename));
406 break;
408 if (bytes_read == 0)
409 break;
410 xwrite_stdout (buffer, bytes_read);
411 n_written += bytes_read;
412 if (n_bytes != COPY_TO_EOF)
414 n_remaining -= bytes_read;
415 if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
416 break;
420 return n_written;
423 /* Call lseek with the specified arguments, where file descriptor FD
424 corresponds to the file, FILENAME.
425 Give a diagnostic and exit nonzero if lseek fails.
426 Otherwise, return the resulting offset. */
428 static off_t
429 xlseek (int fd, off_t offset, int whence, char const *filename)
431 off_t new_offset = lseek (fd, offset, whence);
432 char buf[INT_BUFSIZE_BOUND (off_t)];
433 char *s;
435 if (0 <= new_offset)
436 return new_offset;
438 s = offtostr (offset, buf);
439 switch (whence)
441 case SEEK_SET:
442 error (0, errno, _("%s: cannot seek to offset %s"),
443 filename, s);
444 break;
445 case SEEK_CUR:
446 error (0, errno, _("%s: cannot seek to relative offset %s"),
447 filename, s);
448 break;
449 case SEEK_END:
450 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
451 filename, s);
452 break;
453 default:
454 abort ();
457 exit (EXIT_FAILURE);
460 /* Print the last N_LINES lines from the end of file FD.
461 Go backward through the file, reading `BUFSIZ' bytes at a time (except
462 probably the first), until we hit the start of the file or have
463 read NUMBER newlines.
464 START_POS is the starting position of the read pointer for the file
465 associated with FD (may be nonzero).
466 END_POS is the file offset of EOF (one larger than offset of last byte).
467 Return true if successful. */
469 static bool
470 file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
471 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
473 char buffer[BUFSIZ];
474 size_t bytes_read;
475 off_t pos = end_pos;
477 if (n_lines == 0)
478 return true;
480 /* Set `bytes_read' to the size of the last, probably partial, buffer;
481 0 < `bytes_read' <= `BUFSIZ'. */
482 bytes_read = (pos - start_pos) % BUFSIZ;
483 if (bytes_read == 0)
484 bytes_read = BUFSIZ;
485 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
486 reads will be on block boundaries, which might increase efficiency. */
487 pos -= bytes_read;
488 xlseek (fd, pos, SEEK_SET, pretty_filename);
489 bytes_read = safe_read (fd, buffer, bytes_read);
490 if (bytes_read == SAFE_READ_ERROR)
492 error (0, errno, _("error reading %s"), quote (pretty_filename));
493 return false;
495 *read_pos = pos + bytes_read;
497 /* Count the incomplete line on files that don't end with a newline. */
498 if (bytes_read && buffer[bytes_read - 1] != '\n')
499 --n_lines;
503 /* Scan backward, counting the newlines in this bufferfull. */
505 size_t n = bytes_read;
506 while (n)
508 char const *nl;
509 nl = memrchr (buffer, '\n', n);
510 if (nl == NULL)
511 break;
512 n = nl - buffer;
513 if (n_lines-- == 0)
515 /* If this newline isn't the last character in the buffer,
516 output the part that is after it. */
517 if (n != bytes_read - 1)
518 xwrite_stdout (nl + 1, bytes_read - (n + 1));
519 *read_pos += dump_remainder (pretty_filename, fd,
520 end_pos - (pos + bytes_read));
521 return true;
525 /* Not enough newlines in that bufferfull. */
526 if (pos == start_pos)
528 /* Not enough lines in the file; print everything from
529 start_pos to the end. */
530 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
531 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
532 end_pos);
533 return true;
535 pos -= BUFSIZ;
536 xlseek (fd, pos, SEEK_SET, pretty_filename);
538 bytes_read = safe_read (fd, buffer, BUFSIZ);
539 if (bytes_read == SAFE_READ_ERROR)
541 error (0, errno, _("error reading %s"), quote (pretty_filename));
542 return false;
545 *read_pos = pos + bytes_read;
547 while (bytes_read > 0);
549 return true;
552 /* Print the last N_LINES lines from the end of the standard input,
553 open for reading as pipe FD.
554 Buffer the text as a linked list of LBUFFERs, adding them as needed.
555 Return true if successful. */
557 static bool
558 pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
559 uintmax_t *read_pos)
561 struct linebuffer
563 char buffer[BUFSIZ];
564 size_t nbytes;
565 size_t nlines;
566 struct linebuffer *next;
568 typedef struct linebuffer LBUFFER;
569 LBUFFER *first, *last, *tmp;
570 size_t total_lines = 0; /* Total number of newlines in all buffers. */
571 bool ok = true;
572 size_t n_read; /* Size in bytes of most recent read */
574 first = last = xmalloc (sizeof (LBUFFER));
575 first->nbytes = first->nlines = 0;
576 first->next = NULL;
577 tmp = xmalloc (sizeof (LBUFFER));
579 /* Input is always read into a fresh buffer. */
580 while (1)
582 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
583 if (n_read == 0 || n_read == SAFE_READ_ERROR)
584 break;
585 tmp->nbytes = n_read;
586 *read_pos += n_read;
587 tmp->nlines = 0;
588 tmp->next = NULL;
590 /* Count the number of newlines just read. */
592 char const *buffer_end = tmp->buffer + n_read;
593 char const *p = tmp->buffer;
594 while ((p = memchr (p, '\n', buffer_end - p)))
596 ++p;
597 ++tmp->nlines;
600 total_lines += tmp->nlines;
602 /* If there is enough room in the last buffer read, just append the new
603 one to it. This is because when reading from a pipe, `n_read' can
604 often be very small. */
605 if (tmp->nbytes + last->nbytes < BUFSIZ)
607 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
608 last->nbytes += tmp->nbytes;
609 last->nlines += tmp->nlines;
611 else
613 /* If there's not enough room, link the new buffer onto the end of
614 the list, then either free up the oldest buffer for the next
615 read if that would leave enough lines, or else malloc a new one.
616 Some compaction mechanism is possible but probably not
617 worthwhile. */
618 last = last->next = tmp;
619 if (total_lines - first->nlines > n_lines)
621 tmp = first;
622 total_lines -= first->nlines;
623 first = first->next;
625 else
626 tmp = xmalloc (sizeof (LBUFFER));
630 free (tmp);
632 if (n_read == SAFE_READ_ERROR)
634 error (0, errno, _("error reading %s"), quote (pretty_filename));
635 ok = false;
636 goto free_lbuffers;
639 /* If the file is empty, then bail out. */
640 if (last->nbytes == 0)
641 goto free_lbuffers;
643 /* This prevents a core dump when the pipe contains no newlines. */
644 if (n_lines == 0)
645 goto free_lbuffers;
647 /* Count the incomplete line on files that don't end with a newline. */
648 if (last->buffer[last->nbytes - 1] != '\n')
650 ++last->nlines;
651 ++total_lines;
654 /* Run through the list, printing lines. First, skip over unneeded
655 buffers. */
656 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
657 total_lines -= tmp->nlines;
659 /* Find the correct beginning, then print the rest of the file. */
661 char const *beg = tmp->buffer;
662 char const *buffer_end = tmp->buffer + tmp->nbytes;
663 if (total_lines > n_lines)
665 /* Skip `total_lines' - `n_lines' newlines. We made sure that
666 `total_lines' - `n_lines' <= `tmp->nlines'. */
667 size_t j;
668 for (j = total_lines - n_lines; j; --j)
670 beg = memchr (beg, '\n', buffer_end - beg);
671 assert (beg);
672 ++beg;
676 xwrite_stdout (beg, buffer_end - beg);
679 for (tmp = tmp->next; tmp; tmp = tmp->next)
680 xwrite_stdout (tmp->buffer, tmp->nbytes);
682 free_lbuffers:
683 while (first)
685 tmp = first->next;
686 free (first);
687 first = tmp;
689 return ok;
692 /* Print the last N_BYTES characters from the end of pipe FD.
693 This is a stripped down version of pipe_lines.
694 Return true if successful. */
696 static bool
697 pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
698 uintmax_t *read_pos)
700 struct charbuffer
702 char buffer[BUFSIZ];
703 size_t nbytes;
704 struct charbuffer *next;
706 typedef struct charbuffer CBUFFER;
707 CBUFFER *first, *last, *tmp;
708 size_t i; /* Index into buffers. */
709 size_t total_bytes = 0; /* Total characters in all buffers. */
710 bool ok = true;
711 size_t n_read;
713 first = last = xmalloc (sizeof (CBUFFER));
714 first->nbytes = 0;
715 first->next = NULL;
716 tmp = xmalloc (sizeof (CBUFFER));
718 /* Input is always read into a fresh buffer. */
719 while (1)
721 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
722 if (n_read == 0 || n_read == SAFE_READ_ERROR)
723 break;
724 *read_pos += n_read;
725 tmp->nbytes = n_read;
726 tmp->next = NULL;
728 total_bytes += tmp->nbytes;
729 /* If there is enough room in the last buffer read, just append the new
730 one to it. This is because when reading from a pipe, `nbytes' can
731 often be very small. */
732 if (tmp->nbytes + last->nbytes < BUFSIZ)
734 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
735 last->nbytes += tmp->nbytes;
737 else
739 /* If there's not enough room, link the new buffer onto the end of
740 the list, then either free up the oldest buffer for the next
741 read if that would leave enough characters, or else malloc a new
742 one. Some compaction mechanism is possible but probably not
743 worthwhile. */
744 last = last->next = tmp;
745 if (total_bytes - first->nbytes > n_bytes)
747 tmp = first;
748 total_bytes -= first->nbytes;
749 first = first->next;
751 else
753 tmp = xmalloc (sizeof (CBUFFER));
758 free (tmp);
760 if (n_read == SAFE_READ_ERROR)
762 error (0, errno, _("error reading %s"), quote (pretty_filename));
763 ok = false;
764 goto free_cbuffers;
767 /* Run through the list, printing characters. First, skip over unneeded
768 buffers. */
769 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
770 total_bytes -= tmp->nbytes;
772 /* Find the correct beginning, then print the rest of the file.
773 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
774 if (total_bytes > n_bytes)
775 i = total_bytes - n_bytes;
776 else
777 i = 0;
778 xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
780 for (tmp = tmp->next; tmp; tmp = tmp->next)
781 xwrite_stdout (tmp->buffer, tmp->nbytes);
783 free_cbuffers:
784 while (first)
786 tmp = first->next;
787 free (first);
788 first = tmp;
790 return ok;
793 /* Skip N_BYTES characters from the start of pipe FD, and print
794 any extra characters that were read beyond that.
795 Return 1 on error, 0 if ok, -1 if EOF. */
797 static int
798 start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
799 uintmax_t *read_pos)
801 char buffer[BUFSIZ];
803 while (0 < n_bytes)
805 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
806 if (bytes_read == 0)
807 return -1;
808 if (bytes_read == SAFE_READ_ERROR)
810 error (0, errno, _("error reading %s"), quote (pretty_filename));
811 return 1;
813 read_pos += bytes_read;
814 if (bytes_read <= n_bytes)
815 n_bytes -= bytes_read;
816 else
818 size_t n_remaining = bytes_read - n_bytes;
819 if (n_remaining)
820 xwrite_stdout (&buffer[n_bytes], n_remaining);
821 break;
825 return 0;
828 /* Skip N_LINES lines at the start of file or pipe FD, and print
829 any extra characters that were read beyond that.
830 Return 1 on error, 0 if ok, -1 if EOF. */
832 static int
833 start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
834 uintmax_t *read_pos)
836 if (n_lines == 0)
837 return 0;
839 while (1)
841 char buffer[BUFSIZ];
842 char *p = buffer;
843 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
844 char *buffer_end = buffer + bytes_read;
845 if (bytes_read == 0) /* EOF */
846 return -1;
847 if (bytes_read == SAFE_READ_ERROR) /* error */
849 error (0, errno, _("error reading %s"), quote (pretty_filename));
850 return 1;
853 *read_pos += bytes_read;
855 while ((p = memchr (p, '\n', buffer_end - p)))
857 ++p;
858 if (--n_lines == 0)
860 if (p < buffer_end)
861 xwrite_stdout (p, buffer_end - p);
862 return 0;
868 /* FIXME: describe */
870 static void
871 recheck (struct File_spec *f, bool blocking)
873 /* open/fstat the file and announce if dev/ino have changed */
874 struct stat new_stats;
875 bool ok = true;
876 bool is_stdin = (STREQ (f->name, "-"));
877 bool was_tailable = f->tailable;
878 int prev_errnum = f->errnum;
879 bool new_file;
880 int fd = (is_stdin
881 ? STDIN_FILENO
882 : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
884 assert (valid_file_spec (f));
886 /* If the open fails because the file doesn't exist,
887 then mark the file as not tailable. */
888 f->tailable = !(reopen_inaccessible_files && fd == -1);
890 if (fd == -1 || fstat (fd, &new_stats) < 0)
892 ok = false;
893 f->errnum = errno;
894 if (!f->tailable)
896 if (was_tailable)
898 /* FIXME-maybe: detect the case in which the file first becomes
899 unreadable (perms), and later becomes readable again and can
900 be seen to be the same file (dev/ino). Otherwise, tail prints
901 the entire contents of the file when it becomes readable. */
902 error (0, f->errnum, _("%s has become inaccessible"),
903 quote (pretty_name (f)));
905 else
907 /* say nothing... it's still not tailable */
910 else if (prev_errnum != errno)
912 error (0, errno, "%s", pretty_name (f));
915 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
917 ok = false;
918 f->errnum = -1;
919 error (0, 0, _("%s has been replaced with an untailable file;\
920 giving up on this name"),
921 quote (pretty_name (f)));
922 f->ignore = true;
924 else
926 f->errnum = 0;
929 new_file = false;
930 if (!ok)
932 close_fd (fd, pretty_name (f));
933 close_fd (f->fd, pretty_name (f));
934 f->fd = -1;
936 else if (prev_errnum && prev_errnum != ENOENT)
938 new_file = true;
939 assert (f->fd == -1);
940 error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
942 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
944 new_file = true;
945 if (f->fd == -1)
947 error (0, 0,
948 _("%s has appeared; following end of new file"),
949 quote (pretty_name (f)));
951 else
953 /* Close the old one. */
954 close_fd (f->fd, pretty_name (f));
956 /* File has been replaced (e.g., via log rotation) --
957 tail the new one. */
958 error (0, 0,
959 _("%s has been replaced; following end of new file"),
960 quote (pretty_name (f)));
963 else
965 if (f->fd == -1)
967 /* This happens when one iteration finds the file missing,
968 then the preceding <dev,inode> pair is reused as the
969 file is recreated. */
970 new_file = true;
972 else
974 close_fd (fd, pretty_name (f));
978 if (new_file)
980 /* Start at the beginning of the file. */
981 record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
982 xlseek (fd, 0, SEEK_SET, pretty_name (f));
986 /* Return true if any of the N_FILES files in F are live, i.e., have
987 open file descriptors. */
989 static bool
990 any_live_files (const struct File_spec *f, size_t n_files)
992 size_t i;
994 for (i = 0; i < n_files; i++)
995 if (0 <= f[i].fd)
996 return true;
997 return false;
1000 /* Tail N_FILES files forever, or until killed.
1001 The pertinent information for each file is stored in an entry of F.
1002 Loop over each of them, doing an fstat to see if they have changed size,
1003 and an occasional open/fstat to see if any dev/ino pair has changed.
1004 If none of them have changed size in one iteration, sleep for a
1005 while and try again. Continue until the user interrupts us. */
1007 static void
1008 tail_forever (struct File_spec *f, size_t n_files, double sleep_interval)
1010 /* Use blocking I/O as an optimization, when it's easy. */
1011 bool blocking = (pid == 0 && follow_mode == Follow_descriptor
1012 && n_files == 1 && ! S_ISREG (f[0].mode));
1013 size_t last;
1014 bool writer_is_dead = false;
1016 last = n_files - 1;
1018 while (1)
1020 size_t i;
1021 bool any_input = false;
1023 for (i = 0; i < n_files; i++)
1025 int fd;
1026 char const *name;
1027 mode_t mode;
1028 struct stat stats;
1029 uintmax_t bytes_read;
1031 if (f[i].ignore)
1032 continue;
1034 if (f[i].fd < 0)
1036 recheck (&f[i], blocking);
1037 continue;
1040 fd = f[i].fd;
1041 name = pretty_name (&f[i]);
1042 mode = f[i].mode;
1044 if (f[i].blocking != blocking)
1046 int old_flags = fcntl (fd, F_GETFL);
1047 int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
1048 if (old_flags < 0
1049 || (new_flags != old_flags
1050 && fcntl (fd, F_SETFL, new_flags) == -1))
1052 /* Don't update f[i].blocking if fcntl fails. */
1053 if (S_ISREG (f[i].mode) && errno == EPERM)
1055 /* This happens when using tail -f on a file with
1056 the append-only attribute. */
1058 else
1059 error (EXIT_FAILURE, errno,
1060 _("%s: cannot change nonblocking mode"), name);
1062 else
1063 f[i].blocking = blocking;
1066 if (!f[i].blocking)
1068 if (fstat (fd, &stats) != 0)
1070 f[i].fd = -1;
1071 f[i].errnum = errno;
1072 error (0, errno, "%s", name);
1073 continue;
1076 if (f[i].mode == stats.st_mode
1077 && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
1078 && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
1080 if ((max_n_unchanged_stats_between_opens
1081 <= f[i].n_unchanged_stats++)
1082 && follow_mode == Follow_name)
1084 recheck (&f[i], f[i].blocking);
1085 f[i].n_unchanged_stats = 0;
1087 continue;
1090 /* This file has changed. Print out what we can, and
1091 then keep looping. */
1093 f[i].mtime = get_stat_mtime (&stats);
1094 f[i].mode = stats.st_mode;
1096 /* reset counter */
1097 f[i].n_unchanged_stats = 0;
1099 if (S_ISREG (mode) && stats.st_size < f[i].size)
1101 error (0, 0, _("%s: file truncated"), name);
1102 last = i;
1103 xlseek (fd, stats.st_size, SEEK_SET, name);
1104 f[i].size = stats.st_size;
1105 continue;
1108 if (i != last)
1110 if (print_headers)
1111 write_header (name);
1112 last = i;
1116 bytes_read = dump_remainder (name, fd,
1117 (f[i].blocking
1118 ? COPY_A_BUFFER : COPY_TO_EOF));
1119 any_input |= (bytes_read != 0);
1120 f[i].size += bytes_read;
1123 if (! any_live_files (f, n_files) && ! reopen_inaccessible_files)
1125 error (0, 0, _("no files remaining"));
1126 break;
1129 if ((!any_input || blocking) && fflush (stdout) != 0)
1130 error (EXIT_FAILURE, errno, _("write error"));
1132 /* If nothing was read, sleep and/or check for dead writers. */
1133 if (!any_input)
1135 if (writer_is_dead)
1136 break;
1138 /* Once the writer is dead, read the files once more to
1139 avoid a race condition. */
1140 writer_is_dead = (pid != 0
1141 && kill (pid, 0) != 0
1142 /* Handle the case in which you cannot send a
1143 signal to the writer, so kill fails and sets
1144 errno to EPERM. */
1145 && errno != EPERM);
1147 if (!writer_is_dead && xnanosleep (sleep_interval))
1148 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1154 #if HAVE_INOTIFY
1156 static size_t
1157 wd_hasher (const void *entry, size_t tabsize)
1159 const struct File_spec *spec = entry;
1160 return spec->wd % tabsize;
1163 static bool
1164 wd_comparator (const void *e1, const void *e2)
1166 const struct File_spec *spec1 = e1;
1167 const struct File_spec *spec2 = e2;
1168 return spec1->wd == spec2->wd;
1171 /* Tail N_FILES files forever, or until killed.
1172 Check modifications using the inotify events system. */
1174 static void
1175 tail_forever_inotify (int wd, struct File_spec *f, size_t n_files,
1176 double sleep_interval)
1178 size_t i;
1179 unsigned int max_realloc = 3;
1180 Hash_table *wd_table;
1182 bool found_watchable = false;
1183 bool writer_is_dead = false;
1184 int prev_wd;
1185 size_t evlen = 0;
1186 char *evbuf;
1187 size_t evbuf_off = 0;
1188 size_t len = 0;
1190 wd_table = hash_initialize (n_files, NULL, wd_hasher, wd_comparator, NULL);
1191 if (! wd_table)
1192 xalloc_die ();
1194 /* Add an inotify watch for each watched file. If -F is specified then watch
1195 its parent directory too, in this way when they re-appear we can add them
1196 again to the watch list. */
1197 for (i = 0; i < n_files; i++)
1199 if (!f[i].ignore)
1201 size_t fnlen = strlen (f[i].name);
1202 if (evlen < fnlen)
1203 evlen = fnlen;
1205 f[i].wd = -1;
1207 if (follow_mode == Follow_name)
1209 size_t dirlen = dir_len (f[i].name);
1210 char prev = f[i].name[dirlen];
1211 f[i].basename_start = last_component (f[i].name) - f[i].name;
1213 f[i].name[dirlen] = '\0';
1215 /* It's fine to add the same directory more than once.
1216 In that case the same watch descriptor is returned. */
1217 f[i].parent_wd = inotify_add_watch (wd, dirlen ? f[i].name : ".",
1218 (IN_CREATE | IN_MOVED_TO
1219 | IN_ATTRIB));
1221 f[i].name[dirlen] = prev;
1223 if (f[i].parent_wd < 0)
1225 error (0, errno, _("cannot watch parent directory of %s"),
1226 quote (f[i].name));
1227 continue;
1231 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1233 if (f[i].wd < 0)
1235 if (errno != f[i].errnum)
1236 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1237 continue;
1240 if (hash_insert (wd_table, &(f[i])) == NULL)
1241 xalloc_die ();
1243 found_watchable = true;
1247 if (follow_mode == Follow_descriptor && !found_watchable)
1248 return;
1250 prev_wd = f[n_files - 1].wd;
1252 evlen += sizeof (struct inotify_event) + 1;
1253 evbuf = xmalloc (evlen);
1255 /* Wait for inotify events and handle them. Events on directories make sure
1256 that watched files can be re-added when -F is used.
1257 This loop sleeps on the `safe_read' call until a new event is notified. */
1258 while (1)
1260 char const *name;
1261 struct File_spec *fspec;
1262 uintmax_t bytes_read;
1263 struct stat stats;
1265 struct inotify_event *ev;
1267 /* When watching a PID, ensure that a read from WD will not block
1268 indefinetely. */
1269 if (pid)
1271 if (writer_is_dead)
1272 exit (EXIT_SUCCESS);
1274 writer_is_dead = (kill (pid, 0) != 0 && errno != EPERM);
1276 struct timeval delay; /* how long to wait for file changes. */
1277 if (writer_is_dead)
1278 delay.tv_sec = delay.tv_usec = 0;
1279 else
1281 delay.tv_sec = (time_t) sleep_interval;
1282 delay.tv_usec = 1000000 * (sleep_interval - delay.tv_sec);
1285 fd_set rfd;
1286 FD_ZERO (&rfd);
1287 FD_SET (wd, &rfd);
1289 int file_change = select (wd + 1, &rfd, NULL, NULL, &delay);
1291 if (file_change == 0)
1292 continue;
1293 else if (file_change == -1)
1294 error (EXIT_FAILURE, errno, _("error monitoring inotify event"));
1297 if (len <= evbuf_off)
1299 len = safe_read (wd, evbuf, evlen);
1300 evbuf_off = 0;
1302 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1303 is too small. */
1304 if ((len == 0 || (len == SAFE_READ_ERROR && errno == EINVAL))
1305 && max_realloc--)
1307 len = 0;
1308 evlen *= 2;
1309 evbuf = xrealloc (evbuf, evlen);
1310 continue;
1313 if (len == 0 || len == SAFE_READ_ERROR)
1314 error (EXIT_FAILURE, errno, _("error reading inotify event"));
1317 ev = (struct inotify_event *) (evbuf + evbuf_off);
1318 evbuf_off += sizeof (*ev) + ev->len;
1320 if (ev->len)
1322 for (i = 0; i < n_files; i++)
1324 /* With N=hundreds of frequently-changing files, this O(N^2)
1325 process might be a problem. FIXME: use a hash table? */
1326 if (f[i].parent_wd == ev->wd
1327 && STREQ (ev->name, f[i].name + f[i].basename_start))
1328 break;
1331 /* It is not a watched file. */
1332 if (i == n_files)
1333 continue;
1335 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1337 if (f[i].wd < 0)
1339 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1340 continue;
1343 fspec = &(f[i]);
1344 if (hash_insert (wd_table, fspec) == NULL)
1345 xalloc_die ();
1347 if (follow_mode == Follow_name)
1348 recheck (&(f[i]), false);
1350 else
1352 struct File_spec key;
1353 key.wd = ev->wd;
1354 fspec = hash_lookup (wd_table, &key);
1357 if (! fspec)
1358 continue;
1360 if (ev->mask & (IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF))
1362 if (ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF))
1364 inotify_rm_watch (wd, f[i].wd);
1365 hash_delete (wd_table, &(f[i]));
1367 if (follow_mode == Follow_name)
1368 recheck (fspec, false);
1370 continue;
1373 name = pretty_name (fspec);
1375 if (fstat (fspec->fd, &stats) != 0)
1377 close_fd (fspec->fd, name);
1378 fspec->fd = -1;
1379 fspec->errnum = errno;
1380 continue;
1383 if (S_ISREG (fspec->mode) && stats.st_size < fspec->size)
1385 error (0, 0, _("%s: file truncated"), name);
1386 prev_wd = ev->wd;
1387 xlseek (fspec->fd, stats.st_size, SEEK_SET, name);
1388 fspec->size = stats.st_size;
1391 if (ev->wd != prev_wd)
1393 if (print_headers)
1394 write_header (name);
1395 prev_wd = ev->wd;
1398 bytes_read = dump_remainder (name, fspec->fd, COPY_TO_EOF);
1399 fspec->size += bytes_read;
1401 if (fflush (stdout) != 0)
1402 error (EXIT_FAILURE, errno, _("write error"));
1405 #endif
1407 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1408 Return true if successful. */
1410 static bool
1411 tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1412 uintmax_t *read_pos)
1414 struct stat stats;
1416 if (fstat (fd, &stats))
1418 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1419 return false;
1422 if (from_start)
1424 if ( ! presume_input_pipe
1425 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1427 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1428 *read_pos += n_bytes;
1430 else
1432 int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
1433 if (t)
1434 return t < 0;
1436 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1438 else
1440 if ( ! presume_input_pipe
1441 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1443 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1444 off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename);
1445 off_t diff = end_pos - current_pos;
1446 /* Be careful here. The current position may actually be
1447 beyond the end of the file. */
1448 off_t bytes_remaining = diff < 0 ? 0 : diff;
1449 off_t nb = n_bytes;
1451 if (bytes_remaining <= nb)
1453 /* From the current position to end of file, there are no
1454 more bytes than have been requested. So reposition the
1455 file pointer to the incoming current position and print
1456 everything after that. */
1457 *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1459 else
1461 /* There are more bytes remaining than were requested.
1462 Back up. */
1463 *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename);
1465 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1467 else
1468 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1470 return true;
1473 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1474 Return true if successful. */
1476 static bool
1477 tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1478 uintmax_t *read_pos)
1480 struct stat stats;
1482 if (fstat (fd, &stats))
1484 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1485 return false;
1488 if (from_start)
1490 int t = start_lines (pretty_filename, fd, n_lines, read_pos);
1491 if (t)
1492 return t < 0;
1493 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1495 else
1497 off_t start_pos = -1;
1498 off_t end_pos;
1500 /* Use file_lines only if FD refers to a regular file for
1501 which lseek (... SEEK_END) works. */
1502 if ( ! presume_input_pipe
1503 && S_ISREG (stats.st_mode)
1504 && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
1505 && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
1507 *read_pos = end_pos;
1508 if (end_pos != 0
1509 && ! file_lines (pretty_filename, fd, n_lines,
1510 start_pos, end_pos, read_pos))
1511 return false;
1513 else
1515 /* Under very unlikely circumstances, it is possible to reach
1516 this point after positioning the file pointer to end of file
1517 via the `lseek (...SEEK_END)' above. In that case, reposition
1518 the file pointer back to start_pos before calling pipe_lines. */
1519 if (start_pos != -1)
1520 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1522 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1525 return true;
1528 /* Display the last N_UNITS units of file FILENAME, open for reading
1529 via FD. Set *READ_POS to the position of the input stream pointer.
1530 *READ_POS is usually the number of bytes read and corresponds to an
1531 offset from the beginning of a file. However, it may be larger than
1532 OFF_T_MAX (as for an input pipe), and may also be larger than the
1533 number of bytes read (when an input pointer is initially not at
1534 beginning of file), and may be far greater than the number of bytes
1535 actually read for an input file that is seekable.
1536 Return true if successful. */
1538 static bool
1539 tail (const char *filename, int fd, uintmax_t n_units,
1540 uintmax_t *read_pos)
1542 *read_pos = 0;
1543 if (count_lines)
1544 return tail_lines (filename, fd, n_units, read_pos);
1545 else
1546 return tail_bytes (filename, fd, n_units, read_pos);
1549 /* Display the last N_UNITS units of the file described by F.
1550 Return true if successful. */
1552 static bool
1553 tail_file (struct File_spec *f, uintmax_t n_units)
1555 int fd;
1556 bool ok;
1558 bool is_stdin = (STREQ (f->name, "-"));
1560 if (is_stdin)
1562 have_read_stdin = true;
1563 fd = STDIN_FILENO;
1564 if (O_BINARY && ! isatty (STDIN_FILENO))
1565 xfreopen (NULL, "rb", stdin);
1567 else
1568 fd = open (f->name, O_RDONLY | O_BINARY);
1570 f->tailable = !(reopen_inaccessible_files && fd == -1);
1572 if (fd == -1)
1574 if (forever)
1576 f->fd = -1;
1577 f->errnum = errno;
1578 f->ignore = false;
1579 f->ino = 0;
1580 f->dev = 0;
1582 error (0, errno, _("cannot open %s for reading"),
1583 quote (pretty_name (f)));
1584 ok = false;
1586 else
1588 uintmax_t read_pos;
1590 if (print_headers)
1591 write_header (pretty_name (f));
1592 ok = tail (pretty_name (f), fd, n_units, &read_pos);
1593 if (forever)
1595 struct stat stats;
1597 #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
1598 /* Before the tail function provided `read_pos', there was
1599 a race condition described in the URL below. This sleep
1600 call made the window big enough to exercise the problem. */
1601 sleep (1);
1602 #endif
1603 f->errnum = ok - 1;
1604 if (fstat (fd, &stats) < 0)
1606 ok = false;
1607 f->errnum = errno;
1608 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1610 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1612 error (0, 0, _("%s: cannot follow end of this type of file;\
1613 giving up on this name"),
1614 pretty_name (f));
1615 ok = false;
1616 f->errnum = -1;
1617 f->ignore = true;
1620 if (!ok)
1622 close_fd (fd, pretty_name (f));
1623 f->fd = -1;
1625 else
1627 /* Note: we must use read_pos here, not stats.st_size,
1628 to avoid a race condition described by Ken Raeburn:
1629 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1630 record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
1633 else
1635 if (!is_stdin && close (fd))
1637 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1638 ok = false;
1643 return ok;
1646 /* If obsolete usage is allowed, and the command line arguments are of
1647 the obsolete form and the option string is well-formed, set
1648 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1649 return true. If the command line arguments are obviously incorrect
1650 (e.g., because obsolete usage is not allowed and the arguments are
1651 incorrect for non-obsolete usage), report an error and exit.
1652 Otherwise, return false and don't modify any parameter or global
1653 variable. */
1655 static bool
1656 parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
1658 const char *p;
1659 const char *n_string;
1660 const char *n_string_end;
1661 bool obsolete_usage;
1662 int default_count = DEFAULT_N_LINES;
1663 bool t_from_start;
1664 bool t_count_lines = true;
1665 bool t_forever = false;
1667 /* With the obsolete form, there is one option string and at most
1668 one file argument. Watch out for "-" and "--", though. */
1669 if (! (argc == 2
1670 || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
1671 || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
1672 return false;
1674 obsolete_usage = (posix2_version () < 200112);
1675 p = argv[1];
1677 switch (*p++)
1679 default:
1680 return false;
1682 case '+':
1683 /* Leading "+" is a file name in the non-obsolete form. */
1684 if (!obsolete_usage)
1685 return false;
1687 t_from_start = true;
1688 break;
1690 case '-':
1691 /* In the non-obsolete form, "-" is standard input and "-c"
1692 requires an option-argument. The obsolete multidigit options
1693 are supported as a GNU extension even when conforming to
1694 POSIX 1003.1-2001, so don't complain about them. */
1695 if (!obsolete_usage && !p[p[0] == 'c'])
1696 return false;
1698 t_from_start = false;
1699 break;
1702 n_string = p;
1703 while (ISDIGIT (*p))
1704 p++;
1705 n_string_end = p;
1707 switch (*p)
1709 case 'b': default_count *= 512; /* Fall through. */
1710 case 'c': t_count_lines = false; /* Fall through. */
1711 case 'l': p++; break;
1714 if (*p == 'f')
1716 t_forever = true;
1717 ++p;
1720 if (*p)
1721 return false;
1723 if (n_string == n_string_end)
1724 *n_units = default_count;
1725 else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
1726 & ~LONGINT_INVALID_SUFFIX_CHAR)
1727 != LONGINT_OK)
1728 error (EXIT_FAILURE, 0, _("number in %s is too large"), quote (argv[1]));
1730 /* Set globals. */
1731 from_start = t_from_start;
1732 count_lines = t_count_lines;
1733 forever = t_forever;
1735 return true;
1738 static void
1739 parse_options (int argc, char **argv,
1740 uintmax_t *n_units, enum header_mode *header_mode,
1741 double *sleep_interval)
1743 int c;
1745 while ((c = getopt_long (argc, argv, "c:n:fFqs:v0123456789",
1746 long_options, NULL))
1747 != -1)
1749 switch (c)
1751 case 'F':
1752 forever = true;
1753 follow_mode = Follow_name;
1754 reopen_inaccessible_files = true;
1755 break;
1757 case 'c':
1758 case 'n':
1759 count_lines = (c == 'n');
1760 if (*optarg == '+')
1761 from_start = true;
1762 else if (*optarg == '-')
1763 ++optarg;
1766 strtol_error s_err;
1767 s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkKmMGTPEZY0");
1768 if (s_err != LONGINT_OK)
1770 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1771 (c == 'n'
1772 ? _("invalid number of lines")
1773 : _("invalid number of bytes")));
1776 break;
1778 case 'f':
1779 case LONG_FOLLOW_OPTION:
1780 forever = true;
1781 if (optarg == NULL)
1782 follow_mode = DEFAULT_FOLLOW_MODE;
1783 else
1784 follow_mode = XARGMATCH ("--follow", optarg,
1785 follow_mode_string, follow_mode_map);
1786 break;
1788 case RETRY_OPTION:
1789 reopen_inaccessible_files = true;
1790 break;
1792 case MAX_UNCHANGED_STATS_OPTION:
1793 /* --max-unchanged-stats=N */
1794 if (xstrtoumax (optarg, NULL, 10,
1795 &max_n_unchanged_stats_between_opens,
1797 != LONGINT_OK)
1799 error (EXIT_FAILURE, 0,
1800 _("%s: invalid maximum number of unchanged stats between opens"),
1801 optarg);
1803 break;
1805 case DISABLE_INOTIFY_OPTION:
1806 disable_inotify = true;
1807 break;
1809 case PID_OPTION:
1811 strtol_error s_err;
1812 unsigned long int tmp_ulong;
1813 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1814 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1816 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1818 pid = tmp_ulong;
1820 break;
1822 case PRESUME_INPUT_PIPE_OPTION:
1823 presume_input_pipe = true;
1824 break;
1826 case 'q':
1827 *header_mode = never;
1828 break;
1830 case 's':
1832 double s;
1833 if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
1834 error (EXIT_FAILURE, 0,
1835 _("%s: invalid number of seconds"), optarg);
1836 *sleep_interval = s;
1838 break;
1840 case 'v':
1841 *header_mode = always;
1842 break;
1844 case_GETOPT_HELP_CHAR;
1846 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1848 case '0': case '1': case '2': case '3': case '4':
1849 case '5': case '6': case '7': case '8': case '9':
1850 error (EXIT_FAILURE, 0,
1851 _("option used in invalid context -- %c"), c);
1853 default:
1854 usage (EXIT_FAILURE);
1858 if (reopen_inaccessible_files && follow_mode != Follow_name)
1859 error (0, 0, _("warning: --retry is useful mainly when following by name"));
1861 if (pid && !forever)
1862 error (0, 0,
1863 _("warning: PID ignored; --pid=PID is useful only when following"));
1864 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
1866 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1867 pid = 0;
1872 main (int argc, char **argv)
1874 enum header_mode header_mode = multiple_files;
1875 bool ok = true;
1876 /* If from_start, the number of items to skip before printing; otherwise,
1877 the number of items at the end of the file to print. Although the type
1878 is signed, the value is never negative. */
1879 uintmax_t n_units = DEFAULT_N_LINES;
1880 size_t n_files;
1881 char **file;
1882 struct File_spec *F;
1883 size_t i;
1884 bool obsolete_option;
1886 /* The number of seconds to sleep between iterations.
1887 During one iteration, every file name or descriptor is checked to
1888 see if it has changed. */
1889 double sleep_interval = 1.0;
1891 initialize_main (&argc, &argv);
1892 set_program_name (argv[0]);
1893 setlocale (LC_ALL, "");
1894 bindtextdomain (PACKAGE, LOCALEDIR);
1895 textdomain (PACKAGE);
1897 atexit (close_stdout);
1899 have_read_stdin = false;
1901 count_lines = true;
1902 forever = from_start = print_headers = false;
1903 obsolete_option = parse_obsolete_option (argc, argv, &n_units);
1904 argc -= obsolete_option;
1905 argv += obsolete_option;
1906 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
1908 /* To start printing with item N_UNITS from the start of the file, skip
1909 N_UNITS - 1 items. `tail -n +0' is actually meaningless, but for Unix
1910 compatibility it's treated the same as `tail -n +1'. */
1911 if (from_start)
1913 if (n_units)
1914 --n_units;
1917 if (optind < argc)
1919 n_files = argc - optind;
1920 file = argv + optind;
1922 else
1924 static char *dummy_stdin = (char *) "-";
1925 n_files = 1;
1926 file = &dummy_stdin;
1930 bool found_hyphen = false;
1932 for (i = 0; i < n_files; i++)
1933 if (STREQ (file[i], "-"))
1934 found_hyphen = true;
1936 /* When following by name, there must be a name. */
1937 if (found_hyphen && follow_mode == Follow_name)
1938 error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quote ("-"));
1940 /* When following forever, warn if any file is `-'.
1941 This is only a warning, since tail's output (before a failing seek,
1942 and that from any non-stdin files) might still be useful. */
1943 if (forever && found_hyphen && isatty (STDIN_FILENO))
1944 error (0, 0, _("warning: following standard input"
1945 " indefinitely is ineffective"));
1948 F = xnmalloc (n_files, sizeof *F);
1949 for (i = 0; i < n_files; i++)
1950 F[i].name = file[i];
1952 if (header_mode == always
1953 || (header_mode == multiple_files && n_files > 1))
1954 print_headers = true;
1956 if (O_BINARY && ! isatty (STDOUT_FILENO))
1957 xfreopen (NULL, "wb", stdout);
1959 for (i = 0; i < n_files; i++)
1960 ok &= tail_file (&F[i], n_units);
1962 /* When there is no FILE operand and stdin is a pipe or FIFO
1963 POSIX requires that tail ignore the -f option.
1964 Since we allow multiple FILE operands, we extend that to say:
1965 ignore any "-" operand that corresponds to a pipe or FIFO. */
1966 size_t n_viable = 0;
1967 for (i = 0; i < n_files; i++)
1969 bool is_a_fifo_or_pipe =
1970 (STREQ (F[i].name, "-")
1971 && !F[i].ignore
1972 && 0 <= F[i].fd
1973 && (S_ISFIFO (F[i].mode)
1974 || (HAVE_FIFO_PIPES != 1 && isapipe (F[i].fd))));
1975 if (is_a_fifo_or_pipe)
1976 F[i].ignore = true;
1977 else
1978 ++n_viable;
1981 if (forever && n_viable)
1983 #if HAVE_INOTIFY
1984 /* If the user specifies stdin via a command line argument of "-",
1985 or implicitly by providing no arguments, we won't use inotify.
1986 Technically, on systems with a working /dev/stdin, we *could*,
1987 but would it be worth it? Verifying that it's a real device
1988 and hooked up to stdin is not trivial, while reverting to
1989 non-inotify-based tail_forever is easy and portable. */
1990 bool stdin_cmdline_arg = false;
1992 for (i = 0; i < n_files; i++)
1993 if (!F[i].ignore && STREQ (F[i].name, "-"))
1994 stdin_cmdline_arg = true;
1996 if (!disable_inotify && !stdin_cmdline_arg)
1998 int wd = inotify_init ();
1999 if (wd < 0)
2000 error (0, errno, _("inotify cannot be used, reverting to polling"));
2001 else
2003 /* Flush any output from tail_file, now, since
2004 tail_forever_inotify flushes only after writing,
2005 not before reading. */
2006 if (fflush (stdout) != 0)
2007 error (EXIT_FAILURE, errno, _("write error"));
2009 tail_forever_inotify (wd, F, n_files, sleep_interval);
2011 /* The only way the above returns is upon failure. */
2012 exit (EXIT_FAILURE);
2015 #endif
2016 tail_forever (F, n_files, sleep_interval);
2019 if (have_read_stdin && close (STDIN_FILENO) < 0)
2020 error (EXIT_FAILURE, errno, "-");
2021 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);