tail: adjust type of a local variable
[coreutils.git] / src / tail.c
blobfd44e220def4d4bba729557b07451d6645a40dc9
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 #endif
55 /* The official name of this program (e.g., no `g' prefix). */
56 #define PROGRAM_NAME "tail"
58 #define AUTHORS \
59 proper_name ("Paul Rubin"), \
60 proper_name ("David MacKenzie"), \
61 proper_name ("Ian Lance Taylor"), \
62 proper_name ("Jim Meyering")
64 /* Number of items to tail. */
65 #define DEFAULT_N_LINES 10
67 /* Special values for dump_remainder's N_BYTES parameter. */
68 #define COPY_TO_EOF UINTMAX_MAX
69 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
71 /* FIXME: make Follow_name the default? */
72 #define DEFAULT_FOLLOW_MODE Follow_descriptor
74 enum Follow_mode
76 /* Follow the name of each file: if the file is renamed, try to reopen
77 that name and track the end of the new file if/when it's recreated.
78 This is useful for tracking logs that are occasionally rotated. */
79 Follow_name = 1,
81 /* Follow each descriptor obtained upon opening a file.
82 That means we'll continue to follow the end of a file even after
83 it has been renamed or unlinked. */
84 Follow_descriptor = 2
87 /* The types of files for which tail works. */
88 #define IS_TAILABLE_FILE_TYPE(Mode) \
89 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
91 static char const *const follow_mode_string[] =
93 "descriptor", "name", NULL
96 static enum Follow_mode const follow_mode_map[] =
98 Follow_descriptor, Follow_name,
101 struct File_spec
103 /* The actual file name, or "-" for stdin. */
104 char *name;
106 /* File descriptor on which the file is open; -1 if it's not open. */
107 int fd;
109 /* Attributes of the file the last time we checked. */
110 off_t size;
111 struct timespec mtime;
112 dev_t dev;
113 ino_t ino;
114 mode_t mode;
116 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
117 int blocking;
119 /* The specified name initially referred to a directory or some other
120 type for which tail isn't meaningful. Unlike for a permission problem
121 (tailable, below) once this is set, the name is not checked ever again. */
122 bool ignore;
124 /* See description of DEFAULT_MAX_N_... below. */
125 uintmax_t n_unchanged_stats;
127 /* A file is tailable if it exists, is readable, and is of type
128 IS_TAILABLE_FILE_TYPE. */
129 bool tailable;
131 /* The value of errno seen last time we checked this file. */
132 int errnum;
134 #if HAVE_INOTIFY
135 /* The watch descriptor used by inotify. */
136 int wd;
138 /* The parent directory watch descriptor. It is used only
139 * when Follow_name is used. */
140 int parent_wd;
142 /* Offset in NAME of the basename part. */
143 size_t basename_start;
144 #endif
147 #if HAVE_INOTIFY
148 /* The events mask used with inotify on files. This mask is not used on
149 directories. */
150 const uint32_t inotify_wd_mask = (IN_MODIFY | IN_ATTRIB | IN_DELETE_SELF
151 | IN_MOVE_SELF);
152 #endif
154 /* Keep trying to open a file even if it is inaccessible when tail starts
155 or if it becomes inaccessible later -- useful only with -f. */
156 static bool reopen_inaccessible_files;
158 /* If true, interpret the numeric argument as the number of lines.
159 Otherwise, interpret it as the number of bytes. */
160 static bool count_lines;
162 /* Whether we follow the name of each file or the file descriptor
163 that is initially associated with each name. */
164 static enum Follow_mode follow_mode = Follow_descriptor;
166 /* If true, read from the ends of all specified files until killed. */
167 static bool forever;
169 /* If true, count from start of file instead of end. */
170 static bool from_start;
172 /* If true, print filename headers. */
173 static bool print_headers;
175 /* When to print the filename banners. */
176 enum header_mode
178 multiple_files, always, never
181 /* When tailing a file by name, if there have been this many consecutive
182 iterations for which the file has not changed, then open/fstat
183 the file to determine if that file name is still associated with the
184 same device/inode-number pair as before. This option is meaningful only
185 when following by name. --max-unchanged-stats=N */
186 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
187 static uintmax_t max_n_unchanged_stats_between_opens =
188 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
190 /* The process ID of the process (presumably on the current host)
191 that is writing to all followed files. */
192 static pid_t pid;
194 /* True if we have ever read standard input. */
195 static bool have_read_stdin;
197 /* If nonzero, skip the is-regular-file test used to determine whether
198 to use the lseek optimization. Instead, use the more general (and
199 more expensive) code unconditionally. Intended solely for testing. */
200 static bool presume_input_pipe;
202 /* For long options that have no equivalent short option, use a
203 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
204 enum
206 RETRY_OPTION = CHAR_MAX + 1,
207 MAX_UNCHANGED_STATS_OPTION,
208 PID_OPTION,
209 PRESUME_INPUT_PIPE_OPTION,
210 LONG_FOLLOW_OPTION
213 static struct option const long_options[] =
215 {"bytes", required_argument, NULL, 'c'},
216 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
217 {"lines", required_argument, NULL, 'n'},
218 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
219 {"pid", required_argument, NULL, PID_OPTION},
220 {"-presume-input-pipe", no_argument, NULL,
221 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
222 {"quiet", no_argument, NULL, 'q'},
223 {"retry", no_argument, NULL, RETRY_OPTION},
224 {"silent", no_argument, NULL, 'q'},
225 {"sleep-interval", required_argument, NULL, 's'},
226 {"verbose", no_argument, NULL, 'v'},
227 {GETOPT_HELP_OPTION_DECL},
228 {GETOPT_VERSION_OPTION_DECL},
229 {NULL, 0, NULL, 0}
232 void
233 usage (int status)
235 if (status != EXIT_SUCCESS)
236 fprintf (stderr, _("Try `%s --help' for more information.\n"),
237 program_name);
238 else
240 printf (_("\
241 Usage: %s [OPTION]... [FILE]...\n\
243 program_name);
244 printf (_("\
245 Print the last %d lines of each FILE to standard output.\n\
246 With more than one FILE, precede each with a header giving the file name.\n\
247 With no FILE, or when FILE is -, read standard input.\n\
249 "), DEFAULT_N_LINES);
250 fputs (_("\
251 Mandatory arguments to long options are mandatory for short options too.\n\
252 "), stdout);
253 fputs (_("\
254 -c, --bytes=K output the last K bytes; alternatively, use +K to\n\
255 output bytes starting with the Kth of each file\n\
256 "), stdout);
257 fputs (_("\
258 -f, --follow[={name|descriptor}]\n\
259 output appended data as the file grows;\n\
260 -f, --follow, and --follow=descriptor are\n\
261 equivalent\n\
262 -F same as --follow=name --retry\n\
263 "), stdout);
264 printf (_("\
265 -n, --lines=K output the last K lines, instead of the last %d;\n\
266 or use +K to output lines starting with the Kth\n\
267 --max-unchanged-stats=N\n\
268 with --follow=name, reopen a FILE which has not\n\
269 changed size after N (default %d) iterations\n\
270 to see if it has been unlinked or renamed\n\
271 (this is the usual case of rotated log files)\n\
273 DEFAULT_N_LINES,
274 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
276 fputs (_("\
277 --pid=PID with -f, terminate after process ID, PID dies\n\
278 -q, --quiet, --silent never output headers giving file names\n\
279 --retry keep trying to open a file even when it is or\n\
280 becomes inaccessible; useful when following by\n\
281 name, i.e., with --follow=name\n\
282 "), stdout);
283 fputs (_("\
284 -s, --sleep-interval=S with -f, sleep for approximately S seconds\n\
285 (default 1.0) between iterations\n\
286 -v, --verbose always output headers giving file names\n\
287 "), stdout);
288 fputs (HELP_OPTION_DESCRIPTION, stdout);
289 fputs (VERSION_OPTION_DESCRIPTION, stdout);
290 fputs (_("\
292 If the first character of K (the number of bytes or lines) is a `+',\n\
293 print beginning with the Kth item from the start of each file, otherwise,\n\
294 print the last K items in the file. K may have a multiplier suffix:\n\
295 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
296 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
298 "), stdout);
299 fputs (_("\
300 With --follow (-f), tail defaults to following the file descriptor, which\n\
301 means that even if a tail'ed file is renamed, tail will continue to track\n\
302 its end. \
303 "), stdout);
304 fputs (_("\
305 This default behavior is not desirable when you really want to\n\
306 track the actual name of the file, not the file descriptor (e.g., log\n\
307 rotation). Use --follow=name in that case. That causes tail to track the\n\
308 named file by reopening it periodically to see if it has been removed and\n\
309 recreated by some other program.\n\
310 "), stdout);
311 emit_bug_reporting_address ();
313 exit (status);
316 static bool
317 valid_file_spec (struct File_spec const *f)
319 /* Exactly one of the following subexpressions must be true. */
320 return ((f->fd == -1) ^ (f->errnum == 0));
323 static char const *
324 pretty_name (struct File_spec const *f)
326 return (STREQ (f->name, "-") ? _("standard input") : f->name);
329 static void
330 xwrite_stdout (char const *buffer, size_t n_bytes)
332 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
333 error (EXIT_FAILURE, errno, _("write error"));
336 /* Record a file F with descriptor FD, size SIZE, status ST, and
337 blocking status BLOCKING. */
339 static void
340 record_open_fd (struct File_spec *f, int fd,
341 off_t size, struct stat const *st,
342 int blocking)
344 f->fd = fd;
345 f->size = size;
346 f->mtime = get_stat_mtime (st);
347 f->dev = st->st_dev;
348 f->ino = st->st_ino;
349 f->mode = st->st_mode;
350 f->blocking = blocking;
351 f->n_unchanged_stats = 0;
352 f->ignore = 0;
355 /* Close the file with descriptor FD and name FILENAME. */
357 static void
358 close_fd (int fd, const char *filename)
360 if (fd != -1 && fd != STDIN_FILENO && close (fd))
362 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
366 static void
367 write_header (const char *pretty_filename)
369 static bool first_file = true;
371 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
372 first_file = false;
375 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
376 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
377 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
378 Return the number of bytes read from the file. */
380 static uintmax_t
381 dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
383 uintmax_t n_written;
384 uintmax_t n_remaining = n_bytes;
386 n_written = 0;
387 while (1)
389 char buffer[BUFSIZ];
390 size_t n = MIN (n_remaining, BUFSIZ);
391 size_t bytes_read = safe_read (fd, buffer, n);
392 if (bytes_read == SAFE_READ_ERROR)
394 if (errno != EAGAIN)
395 error (EXIT_FAILURE, errno, _("error reading %s"),
396 quote (pretty_filename));
397 break;
399 if (bytes_read == 0)
400 break;
401 xwrite_stdout (buffer, bytes_read);
402 n_written += bytes_read;
403 if (n_bytes != COPY_TO_EOF)
405 n_remaining -= bytes_read;
406 if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
407 break;
411 return n_written;
414 /* Call lseek with the specified arguments, where file descriptor FD
415 corresponds to the file, FILENAME.
416 Give a diagnostic and exit nonzero if lseek fails.
417 Otherwise, return the resulting offset. */
419 static off_t
420 xlseek (int fd, off_t offset, int whence, char const *filename)
422 off_t new_offset = lseek (fd, offset, whence);
423 char buf[INT_BUFSIZE_BOUND (off_t)];
424 char *s;
426 if (0 <= new_offset)
427 return new_offset;
429 s = offtostr (offset, buf);
430 switch (whence)
432 case SEEK_SET:
433 error (0, errno, _("%s: cannot seek to offset %s"),
434 filename, s);
435 break;
436 case SEEK_CUR:
437 error (0, errno, _("%s: cannot seek to relative offset %s"),
438 filename, s);
439 break;
440 case SEEK_END:
441 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
442 filename, s);
443 break;
444 default:
445 abort ();
448 exit (EXIT_FAILURE);
451 /* Print the last N_LINES lines from the end of file FD.
452 Go backward through the file, reading `BUFSIZ' bytes at a time (except
453 probably the first), until we hit the start of the file or have
454 read NUMBER newlines.
455 START_POS is the starting position of the read pointer for the file
456 associated with FD (may be nonzero).
457 END_POS is the file offset of EOF (one larger than offset of last byte).
458 Return true if successful. */
460 static bool
461 file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
462 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
464 char buffer[BUFSIZ];
465 size_t bytes_read;
466 off_t pos = end_pos;
468 if (n_lines == 0)
469 return true;
471 /* Set `bytes_read' to the size of the last, probably partial, buffer;
472 0 < `bytes_read' <= `BUFSIZ'. */
473 bytes_read = (pos - start_pos) % BUFSIZ;
474 if (bytes_read == 0)
475 bytes_read = BUFSIZ;
476 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
477 reads will be on block boundaries, which might increase efficiency. */
478 pos -= bytes_read;
479 xlseek (fd, pos, SEEK_SET, pretty_filename);
480 bytes_read = safe_read (fd, buffer, bytes_read);
481 if (bytes_read == SAFE_READ_ERROR)
483 error (0, errno, _("error reading %s"), quote (pretty_filename));
484 return false;
486 *read_pos = pos + bytes_read;
488 /* Count the incomplete line on files that don't end with a newline. */
489 if (bytes_read && buffer[bytes_read - 1] != '\n')
490 --n_lines;
494 /* Scan backward, counting the newlines in this bufferfull. */
496 size_t n = bytes_read;
497 while (n)
499 char const *nl;
500 nl = memrchr (buffer, '\n', n);
501 if (nl == NULL)
502 break;
503 n = nl - buffer;
504 if (n_lines-- == 0)
506 /* If this newline isn't the last character in the buffer,
507 output the part that is after it. */
508 if (n != bytes_read - 1)
509 xwrite_stdout (nl + 1, bytes_read - (n + 1));
510 *read_pos += dump_remainder (pretty_filename, fd,
511 end_pos - (pos + bytes_read));
512 return true;
516 /* Not enough newlines in that bufferfull. */
517 if (pos == start_pos)
519 /* Not enough lines in the file; print everything from
520 start_pos to the end. */
521 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
522 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
523 end_pos);
524 return true;
526 pos -= BUFSIZ;
527 xlseek (fd, pos, SEEK_SET, pretty_filename);
529 bytes_read = safe_read (fd, buffer, BUFSIZ);
530 if (bytes_read == SAFE_READ_ERROR)
532 error (0, errno, _("error reading %s"), quote (pretty_filename));
533 return false;
536 *read_pos = pos + bytes_read;
538 while (bytes_read > 0);
540 return true;
543 /* Print the last N_LINES lines from the end of the standard input,
544 open for reading as pipe FD.
545 Buffer the text as a linked list of LBUFFERs, adding them as needed.
546 Return true if successful. */
548 static bool
549 pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
550 uintmax_t *read_pos)
552 struct linebuffer
554 char buffer[BUFSIZ];
555 size_t nbytes;
556 size_t nlines;
557 struct linebuffer *next;
559 typedef struct linebuffer LBUFFER;
560 LBUFFER *first, *last, *tmp;
561 size_t total_lines = 0; /* Total number of newlines in all buffers. */
562 bool ok = true;
563 size_t n_read; /* Size in bytes of most recent read */
565 first = last = xmalloc (sizeof (LBUFFER));
566 first->nbytes = first->nlines = 0;
567 first->next = NULL;
568 tmp = xmalloc (sizeof (LBUFFER));
570 /* Input is always read into a fresh buffer. */
571 while (1)
573 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
574 if (n_read == 0 || n_read == SAFE_READ_ERROR)
575 break;
576 tmp->nbytes = n_read;
577 *read_pos += n_read;
578 tmp->nlines = 0;
579 tmp->next = NULL;
581 /* Count the number of newlines just read. */
583 char const *buffer_end = tmp->buffer + n_read;
584 char const *p = tmp->buffer;
585 while ((p = memchr (p, '\n', buffer_end - p)))
587 ++p;
588 ++tmp->nlines;
591 total_lines += tmp->nlines;
593 /* If there is enough room in the last buffer read, just append the new
594 one to it. This is because when reading from a pipe, `n_read' can
595 often be very small. */
596 if (tmp->nbytes + last->nbytes < BUFSIZ)
598 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
599 last->nbytes += tmp->nbytes;
600 last->nlines += tmp->nlines;
602 else
604 /* If there's not enough room, link the new buffer onto the end of
605 the list, then either free up the oldest buffer for the next
606 read if that would leave enough lines, or else malloc a new one.
607 Some compaction mechanism is possible but probably not
608 worthwhile. */
609 last = last->next = tmp;
610 if (total_lines - first->nlines > n_lines)
612 tmp = first;
613 total_lines -= first->nlines;
614 first = first->next;
616 else
617 tmp = xmalloc (sizeof (LBUFFER));
621 free (tmp);
623 if (n_read == SAFE_READ_ERROR)
625 error (0, errno, _("error reading %s"), quote (pretty_filename));
626 ok = false;
627 goto free_lbuffers;
630 /* If the file is empty, then bail out. */
631 if (last->nbytes == 0)
632 goto free_lbuffers;
634 /* This prevents a core dump when the pipe contains no newlines. */
635 if (n_lines == 0)
636 goto free_lbuffers;
638 /* Count the incomplete line on files that don't end with a newline. */
639 if (last->buffer[last->nbytes - 1] != '\n')
641 ++last->nlines;
642 ++total_lines;
645 /* Run through the list, printing lines. First, skip over unneeded
646 buffers. */
647 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
648 total_lines -= tmp->nlines;
650 /* Find the correct beginning, then print the rest of the file. */
652 char const *beg = tmp->buffer;
653 char const *buffer_end = tmp->buffer + tmp->nbytes;
654 if (total_lines > n_lines)
656 /* Skip `total_lines' - `n_lines' newlines. We made sure that
657 `total_lines' - `n_lines' <= `tmp->nlines'. */
658 size_t j;
659 for (j = total_lines - n_lines; j; --j)
661 beg = memchr (beg, '\n', buffer_end - beg);
662 assert (beg);
663 ++beg;
667 xwrite_stdout (beg, buffer_end - beg);
670 for (tmp = tmp->next; tmp; tmp = tmp->next)
671 xwrite_stdout (tmp->buffer, tmp->nbytes);
673 free_lbuffers:
674 while (first)
676 tmp = first->next;
677 free (first);
678 first = tmp;
680 return ok;
683 /* Print the last N_BYTES characters from the end of pipe FD.
684 This is a stripped down version of pipe_lines.
685 Return true if successful. */
687 static bool
688 pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
689 uintmax_t *read_pos)
691 struct charbuffer
693 char buffer[BUFSIZ];
694 size_t nbytes;
695 struct charbuffer *next;
697 typedef struct charbuffer CBUFFER;
698 CBUFFER *first, *last, *tmp;
699 size_t i; /* Index into buffers. */
700 size_t total_bytes = 0; /* Total characters in all buffers. */
701 bool ok = true;
702 size_t n_read;
704 first = last = xmalloc (sizeof (CBUFFER));
705 first->nbytes = 0;
706 first->next = NULL;
707 tmp = xmalloc (sizeof (CBUFFER));
709 /* Input is always read into a fresh buffer. */
710 while (1)
712 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
713 if (n_read == 0 || n_read == SAFE_READ_ERROR)
714 break;
715 *read_pos += n_read;
716 tmp->nbytes = n_read;
717 tmp->next = NULL;
719 total_bytes += tmp->nbytes;
720 /* If there is enough room in the last buffer read, just append the new
721 one to it. This is because when reading from a pipe, `nbytes' can
722 often be very small. */
723 if (tmp->nbytes + last->nbytes < BUFSIZ)
725 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
726 last->nbytes += tmp->nbytes;
728 else
730 /* If there's not enough room, link the new buffer onto the end of
731 the list, then either free up the oldest buffer for the next
732 read if that would leave enough characters, or else malloc a new
733 one. Some compaction mechanism is possible but probably not
734 worthwhile. */
735 last = last->next = tmp;
736 if (total_bytes - first->nbytes > n_bytes)
738 tmp = first;
739 total_bytes -= first->nbytes;
740 first = first->next;
742 else
744 tmp = xmalloc (sizeof (CBUFFER));
749 free (tmp);
751 if (n_read == SAFE_READ_ERROR)
753 error (0, errno, _("error reading %s"), quote (pretty_filename));
754 ok = false;
755 goto free_cbuffers;
758 /* Run through the list, printing characters. First, skip over unneeded
759 buffers. */
760 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
761 total_bytes -= tmp->nbytes;
763 /* Find the correct beginning, then print the rest of the file.
764 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
765 if (total_bytes > n_bytes)
766 i = total_bytes - n_bytes;
767 else
768 i = 0;
769 xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
771 for (tmp = tmp->next; tmp; tmp = tmp->next)
772 xwrite_stdout (tmp->buffer, tmp->nbytes);
774 free_cbuffers:
775 while (first)
777 tmp = first->next;
778 free (first);
779 first = tmp;
781 return ok;
784 /* Skip N_BYTES characters from the start of pipe FD, and print
785 any extra characters that were read beyond that.
786 Return 1 on error, 0 if ok, -1 if EOF. */
788 static int
789 start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
790 uintmax_t *read_pos)
792 char buffer[BUFSIZ];
794 while (0 < n_bytes)
796 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
797 if (bytes_read == 0)
798 return -1;
799 if (bytes_read == SAFE_READ_ERROR)
801 error (0, errno, _("error reading %s"), quote (pretty_filename));
802 return 1;
804 read_pos += bytes_read;
805 if (bytes_read <= n_bytes)
806 n_bytes -= bytes_read;
807 else
809 size_t n_remaining = bytes_read - n_bytes;
810 if (n_remaining)
811 xwrite_stdout (&buffer[n_bytes], n_remaining);
812 break;
816 return 0;
819 /* Skip N_LINES lines at the start of file or pipe FD, and print
820 any extra characters that were read beyond that.
821 Return 1 on error, 0 if ok, -1 if EOF. */
823 static int
824 start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
825 uintmax_t *read_pos)
827 if (n_lines == 0)
828 return 0;
830 while (1)
832 char buffer[BUFSIZ];
833 char *p = buffer;
834 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
835 char *buffer_end = buffer + bytes_read;
836 if (bytes_read == 0) /* EOF */
837 return -1;
838 if (bytes_read == SAFE_READ_ERROR) /* error */
840 error (0, errno, _("error reading %s"), quote (pretty_filename));
841 return 1;
844 *read_pos += bytes_read;
846 while ((p = memchr (p, '\n', buffer_end - p)))
848 ++p;
849 if (--n_lines == 0)
851 if (p < buffer_end)
852 xwrite_stdout (p, buffer_end - p);
853 return 0;
859 /* FIXME: describe */
861 static void
862 recheck (struct File_spec *f, bool blocking)
864 /* open/fstat the file and announce if dev/ino have changed */
865 struct stat new_stats;
866 bool ok = true;
867 bool is_stdin = (STREQ (f->name, "-"));
868 bool was_tailable = f->tailable;
869 int prev_errnum = f->errnum;
870 bool new_file;
871 int fd = (is_stdin
872 ? STDIN_FILENO
873 : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
875 assert (valid_file_spec (f));
877 /* If the open fails because the file doesn't exist,
878 then mark the file as not tailable. */
879 f->tailable = !(reopen_inaccessible_files && fd == -1);
881 if (fd == -1 || fstat (fd, &new_stats) < 0)
883 ok = false;
884 f->errnum = errno;
885 if (!f->tailable)
887 if (was_tailable)
889 /* FIXME-maybe: detect the case in which the file first becomes
890 unreadable (perms), and later becomes readable again and can
891 be seen to be the same file (dev/ino). Otherwise, tail prints
892 the entire contents of the file when it becomes readable. */
893 error (0, f->errnum, _("%s has become inaccessible"),
894 quote (pretty_name (f)));
896 else
898 /* say nothing... it's still not tailable */
901 else if (prev_errnum != errno)
903 error (0, errno, "%s", pretty_name (f));
906 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
908 ok = false;
909 f->errnum = -1;
910 error (0, 0, _("%s has been replaced with an untailable file;\
911 giving up on this name"),
912 quote (pretty_name (f)));
913 f->ignore = true;
915 else
917 f->errnum = 0;
920 new_file = false;
921 if (!ok)
923 close_fd (fd, pretty_name (f));
924 close_fd (f->fd, pretty_name (f));
925 f->fd = -1;
927 else if (prev_errnum && prev_errnum != ENOENT)
929 new_file = true;
930 assert (f->fd == -1);
931 error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
933 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
935 new_file = true;
936 if (f->fd == -1)
938 error (0, 0,
939 _("%s has appeared; following end of new file"),
940 quote (pretty_name (f)));
942 else
944 /* Close the old one. */
945 close_fd (f->fd, pretty_name (f));
947 /* File has been replaced (e.g., via log rotation) --
948 tail the new one. */
949 error (0, 0,
950 _("%s has been replaced; following end of new file"),
951 quote (pretty_name (f)));
954 else
956 if (f->fd == -1)
958 /* This happens when one iteration finds the file missing,
959 then the preceding <dev,inode> pair is reused as the
960 file is recreated. */
961 new_file = true;
963 else
965 close_fd (fd, pretty_name (f));
969 if (new_file)
971 /* Start at the beginning of the file. */
972 record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
973 xlseek (fd, 0, SEEK_SET, pretty_name (f));
977 /* Return true if any of the N_FILES files in F are live, i.e., have
978 open file descriptors. */
980 static bool
981 any_live_files (const struct File_spec *f, size_t n_files)
983 size_t i;
985 for (i = 0; i < n_files; i++)
986 if (0 <= f[i].fd)
987 return true;
988 return false;
991 /* Tail N_FILES files forever, or until killed.
992 The pertinent information for each file is stored in an entry of F.
993 Loop over each of them, doing an fstat to see if they have changed size,
994 and an occasional open/fstat to see if any dev/ino pair has changed.
995 If none of them have changed size in one iteration, sleep for a
996 while and try again. Continue until the user interrupts us. */
998 static void
999 tail_forever (struct File_spec *f, size_t n_files, double sleep_interval)
1001 /* Use blocking I/O as an optimization, when it's easy. */
1002 bool blocking = (pid == 0 && follow_mode == Follow_descriptor
1003 && n_files == 1 && ! S_ISREG (f[0].mode));
1004 size_t last;
1005 bool writer_is_dead = false;
1007 last = n_files - 1;
1009 while (1)
1011 size_t i;
1012 bool any_input = false;
1014 for (i = 0; i < n_files; i++)
1016 int fd;
1017 char const *name;
1018 mode_t mode;
1019 struct stat stats;
1020 uintmax_t bytes_read;
1022 if (f[i].ignore)
1023 continue;
1025 if (f[i].fd < 0)
1027 recheck (&f[i], blocking);
1028 continue;
1031 fd = f[i].fd;
1032 name = pretty_name (&f[i]);
1033 mode = f[i].mode;
1035 if (f[i].blocking != blocking)
1037 int old_flags = fcntl (fd, F_GETFL);
1038 int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
1039 if (old_flags < 0
1040 || (new_flags != old_flags
1041 && fcntl (fd, F_SETFL, new_flags) == -1))
1043 /* Don't update f[i].blocking if fcntl fails. */
1044 if (S_ISREG (f[i].mode) && errno == EPERM)
1046 /* This happens when using tail -f on a file with
1047 the append-only attribute. */
1049 else
1050 error (EXIT_FAILURE, errno,
1051 _("%s: cannot change nonblocking mode"), name);
1053 else
1054 f[i].blocking = blocking;
1057 if (!f[i].blocking)
1059 if (fstat (fd, &stats) != 0)
1061 f[i].fd = -1;
1062 f[i].errnum = errno;
1063 error (0, errno, "%s", name);
1064 continue;
1067 if (f[i].mode == stats.st_mode
1068 && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
1069 && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
1071 if ((max_n_unchanged_stats_between_opens
1072 <= f[i].n_unchanged_stats++)
1073 && follow_mode == Follow_name)
1075 recheck (&f[i], f[i].blocking);
1076 f[i].n_unchanged_stats = 0;
1078 continue;
1081 /* This file has changed. Print out what we can, and
1082 then keep looping. */
1084 f[i].mtime = get_stat_mtime (&stats);
1085 f[i].mode = stats.st_mode;
1087 /* reset counter */
1088 f[i].n_unchanged_stats = 0;
1090 if (S_ISREG (mode) && stats.st_size < f[i].size)
1092 error (0, 0, _("%s: file truncated"), name);
1093 last = i;
1094 xlseek (fd, stats.st_size, SEEK_SET, name);
1095 f[i].size = stats.st_size;
1096 continue;
1099 if (i != last)
1101 if (print_headers)
1102 write_header (name);
1103 last = i;
1107 bytes_read = dump_remainder (name, fd,
1108 (f[i].blocking
1109 ? COPY_A_BUFFER : COPY_TO_EOF));
1110 any_input |= (bytes_read != 0);
1111 f[i].size += bytes_read;
1114 if (! any_live_files (f, n_files) && ! reopen_inaccessible_files)
1116 error (0, 0, _("no files remaining"));
1117 break;
1120 if ((!any_input | blocking) && fflush (stdout) != 0)
1121 error (EXIT_FAILURE, errno, _("write error"));
1123 /* If nothing was read, sleep and/or check for dead writers. */
1124 if (!any_input)
1126 if (writer_is_dead)
1127 break;
1129 if (xnanosleep (sleep_interval))
1130 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1132 /* Once the writer is dead, read the files once more to
1133 avoid a race condition. */
1134 writer_is_dead = (pid != 0
1135 && kill (pid, 0) != 0
1136 /* Handle the case in which you cannot send a
1137 signal to the writer, so kill fails and sets
1138 errno to EPERM. */
1139 && errno != EPERM);
1144 #if HAVE_INOTIFY
1146 static size_t
1147 wd_hasher (const void *entry, size_t tabsize)
1149 const struct File_spec *spec = entry;
1150 return spec->wd % tabsize;
1153 static bool
1154 wd_comparator (const void *e1, const void *e2)
1156 const struct File_spec *spec1 = e1;
1157 const struct File_spec *spec2 = e2;
1158 return spec1->wd == spec2->wd;
1161 /* Tail N_FILES files forever, or until killed.
1162 Check modifications using the inotify events system. */
1164 static void
1165 tail_forever_inotify (int wd, struct File_spec *f, size_t n_files)
1167 size_t i;
1168 unsigned int max_realloc = 3;
1169 Hash_table *wd_table;
1171 bool found_watchable = false;
1172 int prev_wd;
1173 size_t evlen = 0;
1174 char *evbuf;
1175 size_t evbuf_off = 0;
1176 size_t len = 0;
1178 wd_table = hash_initialize (n_files, NULL, wd_hasher, wd_comparator, NULL);
1179 if (! wd_table)
1180 xalloc_die ();
1182 /* Add an inotify watch for each watched file. If -F is specified then watch
1183 its parent directory too, in this way when they re-appear we can add them
1184 again to the watch list. */
1185 for (i = 0; i < n_files; i++)
1187 if (!f[i].ignore)
1189 size_t fnlen = strlen (f[i].name);
1190 if (evlen < fnlen)
1191 evlen = fnlen;
1193 f[i].wd = 0;
1195 if (follow_mode == Follow_name)
1197 size_t dirlen = dir_len (f[i].name);
1198 char prev = f[i].name[dirlen];
1199 f[i].basename_start = last_component (f[i].name) - f[i].name;
1201 f[i].name[dirlen] = '\0';
1203 /* It's fine to add the same directory more than once.
1204 In that case the same watch descriptor is returned. */
1205 f[i].parent_wd = inotify_add_watch (wd, dirlen ? f[i].name : ".",
1206 (IN_CREATE | IN_MOVED_TO
1207 | IN_ATTRIB));
1209 f[i].name[dirlen] = prev;
1211 if (f[i].parent_wd < 0)
1213 error (0, errno, _("cannot watch parent directory of %s"),
1214 quote (f[i].name));
1215 continue;
1219 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1221 if (f[i].wd < 0)
1223 if (errno != f[i].errnum)
1224 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1225 continue;
1228 if (hash_insert (wd_table, &(f[i])) == NULL)
1229 xalloc_die ();
1231 if (follow_mode == Follow_name || f[i].wd)
1232 found_watchable = true;
1236 if (follow_mode == Follow_descriptor && !found_watchable)
1237 return;
1239 prev_wd = f[n_files - 1].wd;
1241 evlen += sizeof (struct inotify_event) + 1;
1242 evbuf = xmalloc (evlen);
1244 /* Wait for inotify events and handle them. Events on directories make sure
1245 that watched files can be re-added when -F is used.
1246 This loop sleeps on the `safe_read' call until a new event is notified. */
1247 while (1)
1249 char const *name;
1250 struct File_spec *fspec;
1251 uintmax_t bytes_read;
1252 struct stat stats;
1254 struct inotify_event *ev;
1256 if (len <= evbuf_off)
1258 len = safe_read (wd, evbuf, evlen);
1259 evbuf_off = 0;
1261 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1262 is too small. */
1263 if ((len == 0 || (len == SAFE_READ_ERROR && errno == EINVAL))
1264 && max_realloc--)
1266 len = 0;
1267 evlen *= 2;
1268 evbuf = xrealloc (evbuf, evlen);
1269 continue;
1272 if (len == 0 || len == SAFE_READ_ERROR)
1273 error (EXIT_FAILURE, errno, _("error reading inotify event"));
1276 ev = (struct inotify_event *) (evbuf + evbuf_off);
1277 evbuf_off += sizeof (*ev) + ev->len;
1279 if (ev->len)
1281 for (i = 0; i < n_files; i++)
1283 /* With N=hundreds of frequently-changing files, this O(N^2)
1284 process might be a problem. FIXME: use a hash table? */
1285 if (f[i].parent_wd == ev->wd
1286 && STREQ (ev->name, f[i].name + f[i].basename_start))
1287 break;
1290 /* It is not a watched file. */
1291 if (i == n_files)
1292 continue;
1294 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1296 if (f[i].wd < 0)
1298 error (0, errno, _("cannot watch %s"), quote (f[i].name));
1299 continue;
1302 fspec = &(f[i]);
1303 if (hash_insert (wd_table, fspec) == NULL)
1304 xalloc_die ();
1306 if (follow_mode == Follow_name)
1307 recheck (&(f[i]), false);
1309 else
1311 struct File_spec key;
1312 key.wd = ev->wd;
1313 fspec = hash_lookup (wd_table, &key);
1316 if (! fspec)
1317 continue;
1319 if (ev->mask & (IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF))
1321 if (ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF))
1323 inotify_rm_watch (wd, f[i].wd);
1324 hash_delete (wd_table, &(f[i]));
1326 if (follow_mode == Follow_name)
1327 recheck (fspec, false);
1329 continue;
1332 name = pretty_name (fspec);
1334 if (fstat (fspec->fd, &stats) != 0)
1336 close_fd (fspec->fd, name);
1337 fspec->fd = -1;
1338 fspec->errnum = errno;
1339 continue;
1342 if (S_ISREG (fspec->mode) && stats.st_size < fspec->size)
1344 error (0, 0, _("%s: file truncated"), name);
1345 prev_wd = ev->wd;
1346 xlseek (fspec->fd, stats.st_size, SEEK_SET, name);
1347 fspec->size = stats.st_size;
1350 if (ev->wd != prev_wd)
1352 if (print_headers)
1353 write_header (name);
1354 prev_wd = ev->wd;
1357 bytes_read = dump_remainder (name, fspec->fd, COPY_TO_EOF);
1358 fspec->size += bytes_read;
1360 if (fflush (stdout) != 0)
1361 error (EXIT_FAILURE, errno, _("write error"));
1365 #endif
1367 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1368 Return true if successful. */
1370 static bool
1371 tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1372 uintmax_t *read_pos)
1374 struct stat stats;
1376 if (fstat (fd, &stats))
1378 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1379 return false;
1382 if (from_start)
1384 if ( ! presume_input_pipe
1385 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1387 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1388 *read_pos += n_bytes;
1390 else
1392 int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
1393 if (t)
1394 return t < 0;
1396 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1398 else
1400 if ( ! presume_input_pipe
1401 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1403 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1404 off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename);
1405 off_t diff = end_pos - current_pos;
1406 /* Be careful here. The current position may actually be
1407 beyond the end of the file. */
1408 off_t bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
1409 off_t nb = n_bytes;
1411 if (bytes_remaining <= nb)
1413 /* From the current position to end of file, there are no
1414 more bytes than have been requested. So reposition the
1415 file pointer to the incoming current position and print
1416 everything after that. */
1417 *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1419 else
1421 /* There are more bytes remaining than were requested.
1422 Back up. */
1423 *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename);
1425 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1427 else
1428 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1430 return true;
1433 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1434 Return true if successful. */
1436 static bool
1437 tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1438 uintmax_t *read_pos)
1440 struct stat stats;
1442 if (fstat (fd, &stats))
1444 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1445 return false;
1448 if (from_start)
1450 int t = start_lines (pretty_filename, fd, n_lines, read_pos);
1451 if (t)
1452 return t < 0;
1453 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1455 else
1457 off_t start_pos = -1;
1458 off_t end_pos;
1460 /* Use file_lines only if FD refers to a regular file for
1461 which lseek (... SEEK_END) works. */
1462 if ( ! presume_input_pipe
1463 && S_ISREG (stats.st_mode)
1464 && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
1465 && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
1467 *read_pos = end_pos;
1468 if (end_pos != 0
1469 && ! file_lines (pretty_filename, fd, n_lines,
1470 start_pos, end_pos, read_pos))
1471 return false;
1473 else
1475 /* Under very unlikely circumstances, it is possible to reach
1476 this point after positioning the file pointer to end of file
1477 via the `lseek (...SEEK_END)' above. In that case, reposition
1478 the file pointer back to start_pos before calling pipe_lines. */
1479 if (start_pos != -1)
1480 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1482 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1485 return true;
1488 /* Display the last N_UNITS units of file FILENAME, open for reading
1489 via FD. Set *READ_POS to the position of the input stream pointer.
1490 *READ_POS is usually the number of bytes read and corresponds to an
1491 offset from the beginning of a file. However, it may be larger than
1492 OFF_T_MAX (as for an input pipe), and may also be larger than the
1493 number of bytes read (when an input pointer is initially not at
1494 beginning of file), and may be far greater than the number of bytes
1495 actually read for an input file that is seekable.
1496 Return true if successful. */
1498 static bool
1499 tail (const char *filename, int fd, uintmax_t n_units,
1500 uintmax_t *read_pos)
1502 *read_pos = 0;
1503 if (count_lines)
1504 return tail_lines (filename, fd, n_units, read_pos);
1505 else
1506 return tail_bytes (filename, fd, n_units, read_pos);
1509 /* Display the last N_UNITS units of the file described by F.
1510 Return true if successful. */
1512 static bool
1513 tail_file (struct File_spec *f, uintmax_t n_units)
1515 int fd;
1516 bool ok;
1518 bool is_stdin = (STREQ (f->name, "-"));
1520 if (is_stdin)
1522 have_read_stdin = true;
1523 fd = STDIN_FILENO;
1524 if (O_BINARY && ! isatty (STDIN_FILENO))
1525 xfreopen (NULL, "rb", stdin);
1527 else
1528 fd = open (f->name, O_RDONLY | O_BINARY);
1530 f->tailable = !(reopen_inaccessible_files && fd == -1);
1532 if (fd == -1)
1534 if (forever)
1536 f->fd = -1;
1537 f->errnum = errno;
1538 f->ignore = false;
1539 f->ino = 0;
1540 f->dev = 0;
1542 error (0, errno, _("cannot open %s for reading"),
1543 quote (pretty_name (f)));
1544 ok = false;
1546 else
1548 uintmax_t read_pos;
1550 if (print_headers)
1551 write_header (pretty_name (f));
1552 ok = tail (pretty_name (f), fd, n_units, &read_pos);
1553 if (forever)
1555 struct stat stats;
1557 #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
1558 /* Before the tail function provided `read_pos', there was
1559 a race condition described in the URL below. This sleep
1560 call made the window big enough to exercise the problem. */
1561 sleep (1);
1562 #endif
1563 f->errnum = ok - 1;
1564 if (fstat (fd, &stats) < 0)
1566 ok = false;
1567 f->errnum = errno;
1568 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1570 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1572 error (0, 0, _("%s: cannot follow end of this type of file;\
1573 giving up on this name"),
1574 pretty_name (f));
1575 ok = false;
1576 f->errnum = -1;
1577 f->ignore = true;
1580 if (!ok)
1582 close_fd (fd, pretty_name (f));
1583 f->fd = -1;
1585 else
1587 /* Note: we must use read_pos here, not stats.st_size,
1588 to avoid a race condition described by Ken Raeburn:
1589 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1590 record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
1593 else
1595 if (!is_stdin && close (fd))
1597 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1598 ok = false;
1603 return ok;
1606 /* If obsolete usage is allowed, and the command line arguments are of
1607 the obsolete form and the option string is well-formed, set
1608 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1609 return true. If the command line arguments are obviously incorrect
1610 (e.g., because obsolete usage is not allowed and the arguments are
1611 incorrect for non-obsolete usage), report an error and exit.
1612 Otherwise, return false and don't modify any parameter or global
1613 variable. */
1615 static bool
1616 parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
1618 const char *p;
1619 const char *n_string;
1620 const char *n_string_end;
1621 bool obsolete_usage;
1622 int default_count = DEFAULT_N_LINES;
1623 bool t_from_start;
1624 bool t_count_lines = true;
1625 bool t_forever = false;
1627 /* With the obsolete form, there is one option string and at most
1628 one file argument. Watch out for "-" and "--", though. */
1629 if (! (argc == 2
1630 || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
1631 || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
1632 return false;
1634 obsolete_usage = (posix2_version () < 200112);
1635 p = argv[1];
1637 switch (*p++)
1639 default:
1640 return false;
1642 case '+':
1643 /* Leading "+" is a file name in the non-obsolete form. */
1644 if (!obsolete_usage)
1645 return false;
1647 t_from_start = true;
1648 break;
1650 case '-':
1651 /* In the non-obsolete form, "-" is standard input and "-c"
1652 requires an option-argument. The obsolete multidigit options
1653 are supported as a GNU extension even when conforming to
1654 POSIX 1003.1-2001, so don't complain about them. */
1655 if (!obsolete_usage && !p[p[0] == 'c'])
1656 return false;
1658 t_from_start = false;
1659 break;
1662 n_string = p;
1663 while (ISDIGIT (*p))
1664 p++;
1665 n_string_end = p;
1667 switch (*p)
1669 case 'b': default_count *= 512; /* Fall through. */
1670 case 'c': t_count_lines = false; /* Fall through. */
1671 case 'l': p++; break;
1674 if (*p == 'f')
1676 t_forever = true;
1677 ++p;
1680 if (*p)
1681 return false;
1683 if (n_string == n_string_end)
1684 *n_units = default_count;
1685 else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
1686 & ~LONGINT_INVALID_SUFFIX_CHAR)
1687 != LONGINT_OK)
1688 error (EXIT_FAILURE, 0, _("number in %s is too large"), quote (argv[1]));
1690 /* Set globals. */
1691 from_start = t_from_start;
1692 count_lines = t_count_lines;
1693 forever = t_forever;
1695 return true;
1698 static void
1699 parse_options (int argc, char **argv,
1700 uintmax_t *n_units, enum header_mode *header_mode,
1701 double *sleep_interval)
1703 int c;
1705 while ((c = getopt_long (argc, argv, "c:n:fFqs:v0123456789",
1706 long_options, NULL))
1707 != -1)
1709 switch (c)
1711 case 'F':
1712 forever = true;
1713 follow_mode = Follow_name;
1714 reopen_inaccessible_files = true;
1715 break;
1717 case 'c':
1718 case 'n':
1719 count_lines = (c == 'n');
1720 if (*optarg == '+')
1721 from_start = true;
1722 else if (*optarg == '-')
1723 ++optarg;
1726 strtol_error s_err;
1727 s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkKmMGTPEZY0");
1728 if (s_err != LONGINT_OK)
1730 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1731 (c == 'n'
1732 ? _("invalid number of lines")
1733 : _("invalid number of bytes")));
1736 break;
1738 case 'f':
1739 case LONG_FOLLOW_OPTION:
1740 forever = true;
1741 if (optarg == NULL)
1742 follow_mode = DEFAULT_FOLLOW_MODE;
1743 else
1744 follow_mode = XARGMATCH ("--follow", optarg,
1745 follow_mode_string, follow_mode_map);
1746 break;
1748 case RETRY_OPTION:
1749 reopen_inaccessible_files = true;
1750 break;
1752 case MAX_UNCHANGED_STATS_OPTION:
1753 /* --max-unchanged-stats=N */
1754 if (xstrtoumax (optarg, NULL, 10,
1755 &max_n_unchanged_stats_between_opens,
1757 != LONGINT_OK)
1759 error (EXIT_FAILURE, 0,
1760 _("%s: invalid maximum number of unchanged stats between opens"),
1761 optarg);
1763 break;
1765 case PID_OPTION:
1767 strtol_error s_err;
1768 unsigned long int tmp_ulong;
1769 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1770 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1772 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1774 pid = tmp_ulong;
1776 break;
1778 case PRESUME_INPUT_PIPE_OPTION:
1779 presume_input_pipe = true;
1780 break;
1782 case 'q':
1783 *header_mode = never;
1784 break;
1786 case 's':
1788 double s;
1789 if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
1790 error (EXIT_FAILURE, 0,
1791 _("%s: invalid number of seconds"), optarg);
1792 *sleep_interval = s;
1794 break;
1796 case 'v':
1797 *header_mode = always;
1798 break;
1800 case_GETOPT_HELP_CHAR;
1802 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1804 case '0': case '1': case '2': case '3': case '4':
1805 case '5': case '6': case '7': case '8': case '9':
1806 error (EXIT_FAILURE, 0,
1807 _("option used in invalid context -- %c"), c);
1809 default:
1810 usage (EXIT_FAILURE);
1814 if (reopen_inaccessible_files && follow_mode != Follow_name)
1815 error (0, 0, _("warning: --retry is useful mainly when following by name"));
1817 if (pid && !forever)
1818 error (0, 0,
1819 _("warning: PID ignored; --pid=PID is useful only when following"));
1820 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
1822 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1823 pid = 0;
1828 main (int argc, char **argv)
1830 enum header_mode header_mode = multiple_files;
1831 bool ok = true;
1832 /* If from_start, the number of items to skip before printing; otherwise,
1833 the number of items at the end of the file to print. Although the type
1834 is signed, the value is never negative. */
1835 uintmax_t n_units = DEFAULT_N_LINES;
1836 size_t n_files;
1837 char **file;
1838 struct File_spec *F;
1839 size_t i;
1840 bool obsolete_option;
1842 /* The number of seconds to sleep between iterations.
1843 During one iteration, every file name or descriptor is checked to
1844 see if it has changed. */
1845 double sleep_interval = 1.0;
1847 initialize_main (&argc, &argv);
1848 set_program_name (argv[0]);
1849 setlocale (LC_ALL, "");
1850 bindtextdomain (PACKAGE, LOCALEDIR);
1851 textdomain (PACKAGE);
1853 atexit (close_stdout);
1855 have_read_stdin = false;
1857 count_lines = true;
1858 forever = from_start = print_headers = false;
1859 obsolete_option = parse_obsolete_option (argc, argv, &n_units);
1860 argc -= obsolete_option;
1861 argv += obsolete_option;
1862 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
1864 /* To start printing with item N_UNITS from the start of the file, skip
1865 N_UNITS - 1 items. `tail -n +0' is actually meaningless, but for Unix
1866 compatibility it's treated the same as `tail -n +1'. */
1867 if (from_start)
1869 if (n_units)
1870 --n_units;
1873 if (optind < argc)
1875 n_files = argc - optind;
1876 file = argv + optind;
1878 else
1880 static char *dummy_stdin = (char *) "-";
1881 n_files = 1;
1882 file = &dummy_stdin;
1884 /* POSIX says that -f is ignored if no file operand is specified
1885 and standard input is a pipe. However, the GNU coding
1886 standards say that program behavior should not depend on
1887 device type, because device independence is an important
1888 principle of the system's design.
1890 Follow the POSIX requirement only if POSIXLY_CORRECT is set. */
1892 if (forever && getenv ("POSIXLY_CORRECT"))
1894 struct stat st;
1895 int is_a_fifo_or_pipe =
1896 (fstat (STDIN_FILENO, &st) != 0 ? -1
1897 : S_ISFIFO (st.st_mode) ? 1
1898 : HAVE_FIFO_PIPES == 1 ? 0
1899 : isapipe (STDIN_FILENO));
1900 if (is_a_fifo_or_pipe < 0)
1901 error (EXIT_FAILURE, errno, _("standard input"));
1902 if (is_a_fifo_or_pipe)
1903 forever = false;
1908 bool found_hyphen = false;
1910 for (i = 0; i < n_files; i++)
1911 if (STREQ (file[i], "-"))
1912 found_hyphen = true;
1914 /* When following by name, there must be a name. */
1915 if (found_hyphen && follow_mode == Follow_name)
1916 error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quote ("-"));
1918 /* When following forever, warn if any file is `-'.
1919 This is only a warning, since tail's output (before a failing seek,
1920 and that from any non-stdin files) might still be useful. */
1921 if (forever && found_hyphen && isatty (STDIN_FILENO))
1922 error (0, 0, _("warning: following standard input"
1923 " indefinitely is ineffective"));
1926 F = xnmalloc (n_files, sizeof *F);
1927 for (i = 0; i < n_files; i++)
1928 F[i].name = file[i];
1930 if (header_mode == always
1931 || (header_mode == multiple_files && n_files > 1))
1932 print_headers = true;
1934 if (O_BINARY && ! isatty (STDOUT_FILENO))
1935 xfreopen (NULL, "wb", stdout);
1937 for (i = 0; i < n_files; i++)
1938 ok &= tail_file (&F[i], n_units);
1940 if (forever)
1942 #if HAVE_INOTIFY
1943 if (pid == 0)
1945 int wd = inotify_init ();
1946 if (wd < 0)
1947 error (0, errno, _("inotify cannot be used, reverting to polling"));
1948 else
1950 tail_forever_inotify (wd, F, n_files);
1952 /* The only way the above returns is upon failure. */
1953 exit (EXIT_FAILURE);
1956 #endif
1957 tail_forever (F, n_files, sleep_interval);
1960 if (have_read_stdin && close (STDIN_FILENO) < 0)
1961 error (EXIT_FAILURE, errno, "-");
1962 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);