source: trunk/coreutils/src/tail.c@ 2662

Last change on this file since 2662 was 2554, checked in by bird, 20 years ago

coretuils-5.94

File size: 44.9 KB
Line 
1/* tail -- output the last part of file(s)
2 Copyright (C) 1989, 90, 91, 1995-2005 Free Software Foundation, Inc.
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
7 any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
17
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.
21
22 Original version by Paul Rubin <[email protected]>.
23 Extensions by David MacKenzie <[email protected]>.
24 tail -f for multiple files by Ian Lance Taylor <[email protected]>. */
25
26#include <config.h>
27
28#include <stdio.h>
29#include <assert.h>
30#include <getopt.h>
31#include <sys/types.h>
32#include <signal.h>
33
34#include "system.h"
35#include "argmatch.h"
36#include "c-strtod.h"
37#include "error.h"
38#include "fcntl--.h"
39#include "inttostr.h"
40#include "posixver.h"
41#include "quote.h"
42#include "safe-read.h"
43#include "stat-time.h"
44#include "xnanosleep.h"
45#include "xstrtol.h"
46#include "xstrtod.h"
47
48/* The official name of this program (e.g., no `g' prefix). */
49#define PROGRAM_NAME "tail"
50
51#define AUTHORS \
52 "Paul Rubin", "David MacKenzie, Ian Lance Taylor", "Jim Meyering"
53
54#ifndef ENOSYS
55 /* Some systems don't have ENOSYS -- this should be a big enough
56 value that no valid errno value will match it. */
57# define ENOSYS 99999
58#endif
59
60/* Number of items to tail. */
61#define DEFAULT_N_LINES 10
62
63/* Special values for dump_remainder's N_BYTES parameter. */
64#define COPY_TO_EOF UINTMAX_MAX
65#define COPY_A_BUFFER (UINTMAX_MAX - 1)
66
67/* FIXME: make Follow_name the default? */
68#define DEFAULT_FOLLOW_MODE Follow_descriptor
69
70enum Follow_mode
71{
72 /* Follow the name of each file: if the file is renamed, try to reopen
73 that name and track the end of the new file if/when it's recreated.
74 This is useful for tracking logs that are occasionally rotated. */
75 Follow_name = 1,
76
77 /* Follow each descriptor obtained upon opening a file.
78 That means we'll continue to follow the end of a file even after
79 it has been renamed or unlinked. */
80 Follow_descriptor = 2
81};
82
83/* On Darwin 7.7, when reading from a command-line pipe, standard
84 input is of type S_ISSOCK. Everywhere else it's S_ISFIFO. */
85#define IS_PIPE_LIKE_FILE_TYPE(Mode) \
86 (S_ISFIFO (Mode) || S_ISSOCK (Mode))
87
88/* The types of files for which tail works. */
89#define IS_TAILABLE_FILE_TYPE(Mode) \
90 (S_ISREG (Mode) || IS_PIPE_LIKE_FILE_TYPE (Mode) || S_ISCHR (Mode))
91
92static char const *const follow_mode_string[] =
93{
94 "descriptor", "name", NULL
95};
96
97static enum Follow_mode const follow_mode_map[] =
98{
99 Follow_descriptor, Follow_name,
100};
101
102struct File_spec
103{
104 /* The actual file name, or "-" for stdin. */
105 char *name;
106
107 /* File descriptor on which the file is open; -1 if it's not open. */
108 int fd;
109
110 /* Attributes of the file the last time we checked. */
111 off_t size;
112 struct timespec mtime;
113 dev_t dev;
114 ino_t ino;
115 mode_t mode;
116
117 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
118 int blocking;
119
120 /* The specified name initially referred to a directory or some other
121 type for which tail isn't meaningful. Unlike for a permission problem
122 (tailable, below) once this is set, the name is not checked ever again. */
123 bool ignore;
124
125 /* See description of DEFAULT_MAX_N_... below. */
126 uintmax_t n_unchanged_stats;
127
128 /* A file is tailable if it exists, is readable, and is of type
129 IS_TAILABLE_FILE_TYPE. */
130 bool tailable;
131
132 /* The value of errno seen last time we checked this file. */
133 int errnum;
134
135};
136
137/* Keep trying to open a file even if it is inaccessible when tail starts
138 or if it becomes inaccessible later -- useful only with -f. */
139static bool reopen_inaccessible_files;
140
141/* If true, interpret the numeric argument as the number of lines.
142 Otherwise, interpret it as the number of bytes. */
143static bool count_lines;
144
145/* Whether we follow the name of each file or the file descriptor
146 that is initially associated with each name. */
147static enum Follow_mode follow_mode = Follow_descriptor;
148
149/* If true, read from the ends of all specified files until killed. */
150static bool forever;
151
152/* If true, count from start of file instead of end. */
153static bool from_start;
154
155/* If true, print filename headers. */
156static bool print_headers;
157
158/* When to print the filename banners. */
159enum header_mode
160{
161 multiple_files, always, never
162};
163
164/* When tailing a file by name, if there have been this many consecutive
165 iterations for which the file has not changed, then open/fstat
166 the file to determine if that file name is still associated with the
167 same device/inode-number pair as before. This option is meaningful only
168 when following by name. --max-unchanged-stats=N */
169#define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
170static uintmax_t max_n_unchanged_stats_between_opens =
171 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
172
173/* The name this program was run with. */
174char *program_name;
175
176/* The process ID of the process (presumably on the current host)
177 that is writing to all followed files. */
178static pid_t pid;
179
180/* True if we have ever read standard input. */
181static bool have_read_stdin;
182
183/* If nonzero, skip the is-regular-file test used to determine whether
184 to use the lseek optimization. Instead, use the more general (and
185 more expensive) code unconditionally. Intended solely for testing. */
186static bool presume_input_pipe;
187
188/* For long options that have no equivalent short option, use a
189 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
190enum
191{
192 RETRY_OPTION = CHAR_MAX + 1,
193 MAX_UNCHANGED_STATS_OPTION,
194 PID_OPTION,
195 PRESUME_INPUT_PIPE_OPTION,
196 LONG_FOLLOW_OPTION
197};
198
199static struct option const long_options[] =
200{
201 {"bytes", required_argument, NULL, 'c'},
202 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
203 {"lines", required_argument, NULL, 'n'},
204 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
205 {"pid", required_argument, NULL, PID_OPTION},
206 {"presume-input-pipe", no_argument, NULL,
207 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
208 {"quiet", no_argument, NULL, 'q'},
209 {"retry", no_argument, NULL, RETRY_OPTION},
210 {"silent", no_argument, NULL, 'q'},
211 {"sleep-interval", required_argument, NULL, 's'},
212 {"verbose", no_argument, NULL, 'v'},
213 {GETOPT_HELP_OPTION_DECL},
214 {GETOPT_VERSION_OPTION_DECL},
215 {NULL, 0, NULL, 0}
216};
217
218void
219usage (int status)
220{
221 if (status != EXIT_SUCCESS)
222 fprintf (stderr, _("Try `%s --help' for more information.\n"),
223 program_name);
224 else
225 {
226 printf (_("\
227Usage: %s [OPTION]... [FILE]...\n\
228"),
229 program_name);
230 printf (_("\
231Print the last %d lines of each FILE to standard output.\n\
232With more than one FILE, precede each with a header giving the file name.\n\
233With no FILE, or when FILE is -, read standard input.\n\
234\n\
235"), DEFAULT_N_LINES);
236 fputs (_("\
237Mandatory arguments to long options are mandatory for short options too.\n\
238"), stdout);
239 fputs (_("\
240 --retry keep trying to open a file even if it is\n\
241 inaccessible when tail starts or if it becomes\n\
242 inaccessible later; useful when following by name,\n\
243 i.e., with --follow=name\n\
244 -c, --bytes=N output the last N bytes\n\
245"), stdout);
246 fputs (_("\
247 -f, --follow[={name|descriptor}]\n\
248 output appended data as the file grows;\n\
249 -f, --follow, and --follow=descriptor are\n\
250 equivalent\n\
251 -F same as --follow=name --retry\n\
252"), stdout);
253 printf (_("\
254 -n, --lines=N output the last N lines, instead of the last %d\n\
255 --max-unchanged-stats=N\n\
256 with --follow=name, reopen a FILE which has not\n\
257 changed size after N (default %d) iterations\n\
258 to see if it has been unlinked or renamed\n\
259 (this is the usual case of rotated log files)\n\
260"),
261 DEFAULT_N_LINES,
262 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
263 );
264 fputs (_("\
265 --pid=PID with -f, terminate after process ID, PID dies\n\
266 -q, --quiet, --silent never output headers giving file names\n\
267 -s, --sleep-interval=S with -f, sleep for approximately S seconds\n\
268 (default 1.0) between iterations.\n\
269 -v, --verbose always output headers giving file names\n\
270"), stdout);
271 fputs (HELP_OPTION_DESCRIPTION, stdout);
272 fputs (VERSION_OPTION_DESCRIPTION, stdout);
273 fputs (_("\
274\n\
275If the first character of N (the number of bytes or lines) is a `+',\n\
276print beginning with the Nth item from the start of each file, otherwise,\n\
277print the last N items in the file. N may have a multiplier suffix:\n\
278b 512, k 1024, m 1024*1024.\n\
279\n\
280"), stdout);
281 fputs (_("\
282With --follow (-f), tail defaults to following the file descriptor, which\n\
283means that even if a tail'ed file is renamed, tail will continue to track\n\
284its end. \
285"), stdout);
286 fputs (_("\
287This default behavior is not desirable when you really want to\n\
288track the actual name of the file, not the file descriptor (e.g., log\n\
289rotation). Use --follow=name in that case. That causes tail to track the\n\
290named file by reopening it periodically to see if it has been removed and\n\
291recreated by some other program.\n\
292"), stdout);
293 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
294 }
295 exit (status);
296}
297
298static bool
299valid_file_spec (struct File_spec const *f)
300{
301 /* Exactly one of the following subexpressions must be true. */
302 return ((f->fd == -1) ^ (f->errnum == 0));
303}
304
305static char *
306pretty_name (struct File_spec const *f)
307{
308 return (STREQ (f->name, "-") ? "standard input" : f->name);
309}
310
311static void
312xwrite_stdout (char const *buffer, size_t n_bytes)
313{
314 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) == 0)
315 error (EXIT_FAILURE, errno, _("write error"));
316}
317
318/* Record a file F with descriptor FD, size SIZE, status ST, and
319 blocking status BLOCKING. */
320
321static void
322record_open_fd (struct File_spec *f, int fd,
323 off_t size, struct stat const *st,
324 int blocking)
325{
326 f->fd = fd;
327 f->size = size;
328 f->mtime = get_stat_mtime (st);
329 f->dev = st->st_dev;
330 f->ino = st->st_ino;
331 f->mode = st->st_mode;
332 f->blocking = blocking;
333 f->n_unchanged_stats = 0;
334 f->ignore = 0;
335}
336
337/* Close the file with descriptor FD and name FILENAME. */
338
339static void
340close_fd (int fd, const char *filename)
341{
342 if (fd != -1 && fd != STDIN_FILENO && close (fd))
343 {
344 error (0, errno, _("closing %s (fd=%d)"), filename, fd);
345 }
346}
347
348static void
349write_header (const char *pretty_filename)
350{
351 static bool first_file = true;
352
353 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
354 first_file = false;
355}
356
357/* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
358 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
359 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
360 Return the number of bytes read from the file. */
361
362static uintmax_t
363dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
364{
365 uintmax_t n_written;
366 uintmax_t n_remaining = n_bytes;
367
368 n_written = 0;
369 while (1)
370 {
371 char buffer[BUFSIZ];
372 size_t n = MIN (n_remaining, BUFSIZ);
373 size_t bytes_read = safe_read (fd, buffer, n);
374 if (bytes_read == SAFE_READ_ERROR)
375 {
376 if (errno != EAGAIN)
377 error (EXIT_FAILURE, errno, _("error reading %s"),
378 quote (pretty_filename));
379 break;
380 }
381 if (bytes_read == 0)
382 break;
383 xwrite_stdout (buffer, bytes_read);
384 n_written += bytes_read;
385 if (n_bytes != COPY_TO_EOF)
386 {
387 n_remaining -= bytes_read;
388 if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
389 break;
390 }
391 }
392
393 return n_written;
394}
395
396/* Call lseek with the specified arguments, where file descriptor FD
397 corresponds to the file, FILENAME.
398 Give a diagnostic and exit nonzero if lseek fails.
399 Otherwise, return the resulting offset. */
400
401static off_t
402xlseek (int fd, off_t offset, int whence, char const *filename)
403{
404 off_t new_offset = lseek (fd, offset, whence);
405 char buf[INT_BUFSIZE_BOUND (off_t)];
406 char *s;
407
408 if (0 <= new_offset)
409 return new_offset;
410
411 s = offtostr (offset, buf);
412 switch (whence)
413 {
414 case SEEK_SET:
415 error (0, errno, _("%s: cannot seek to offset %s"),
416 filename, s);
417 break;
418 case SEEK_CUR:
419 error (0, errno, _("%s: cannot seek to relative offset %s"),
420 filename, s);
421 break;
422 case SEEK_END:
423 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
424 filename, s);
425 break;
426 default:
427 abort ();
428 }
429
430 exit (EXIT_FAILURE);
431}
432
433/* Print the last N_LINES lines from the end of file FD.
434 Go backward through the file, reading `BUFSIZ' bytes at a time (except
435 probably the first), until we hit the start of the file or have
436 read NUMBER newlines.
437 START_POS is the starting position of the read pointer for the file
438 associated with FD (may be nonzero).
439 END_POS is the file offset of EOF (one larger than offset of last byte).
440 Return true if successful. */
441
442static bool
443file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
444 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
445{
446 char buffer[BUFSIZ];
447 size_t bytes_read;
448 off_t pos = end_pos;
449
450 if (n_lines == 0)
451 return true;
452
453 /* Set `bytes_read' to the size of the last, probably partial, buffer;
454 0 < `bytes_read' <= `BUFSIZ'. */
455 bytes_read = (pos - start_pos) % BUFSIZ;
456 if (bytes_read == 0)
457 bytes_read = BUFSIZ;
458 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
459 reads will be on block boundaries, which might increase efficiency. */
460 pos -= bytes_read;
461 xlseek (fd, pos, SEEK_SET, pretty_filename);
462 bytes_read = safe_read (fd, buffer, bytes_read);
463 if (bytes_read == SAFE_READ_ERROR)
464 {
465 error (0, errno, _("error reading %s"), quote (pretty_filename));
466 return false;
467 }
468 *read_pos = pos + bytes_read;
469
470 /* Count the incomplete line on files that don't end with a newline. */
471 if (bytes_read && buffer[bytes_read - 1] != '\n')
472 --n_lines;
473
474 do
475 {
476 /* Scan backward, counting the newlines in this bufferfull. */
477
478 size_t n = bytes_read;
479 while (n)
480 {
481 char const *nl;
482 nl = memrchr (buffer, '\n', n);
483 if (nl == NULL)
484 break;
485 n = nl - buffer;
486 if (n_lines-- == 0)
487 {
488 /* If this newline isn't the last character in the buffer,
489 output the part that is after it. */
490 if (n != bytes_read - 1)
491 xwrite_stdout (nl + 1, bytes_read - (n + 1));
492 *read_pos += dump_remainder (pretty_filename, fd,
493 end_pos - (pos + bytes_read));
494 return true;
495 }
496 }
497
498 /* Not enough newlines in that bufferfull. */
499 if (pos == start_pos)
500 {
501 /* Not enough lines in the file; print everything from
502 start_pos to the end. */
503 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
504 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
505 end_pos);
506 return true;
507 }
508 pos -= BUFSIZ;
509 xlseek (fd, pos, SEEK_SET, pretty_filename);
510
511 bytes_read = safe_read (fd, buffer, BUFSIZ);
512 if (bytes_read == SAFE_READ_ERROR)
513 {
514 error (0, errno, _("error reading %s"), quote (pretty_filename));
515 return false;
516 }
517
518 *read_pos = pos + bytes_read;
519 }
520 while (bytes_read > 0);
521
522 return true;
523}
524
525/* Print the last N_LINES lines from the end of the standard input,
526 open for reading as pipe FD.
527 Buffer the text as a linked list of LBUFFERs, adding them as needed.
528 Return true if successful. */
529
530static bool
531pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
532 uintmax_t *read_pos)
533{
534 struct linebuffer
535 {
536 char buffer[BUFSIZ];
537 size_t nbytes;
538 size_t nlines;
539 struct linebuffer *next;
540 };
541 typedef struct linebuffer LBUFFER;
542 LBUFFER *first, *last, *tmp;
543 size_t total_lines = 0; /* Total number of newlines in all buffers. */
544 bool ok = true;
545 size_t n_read; /* Size in bytes of most recent read */
546
547 first = last = xmalloc (sizeof (LBUFFER));
548 first->nbytes = first->nlines = 0;
549 first->next = NULL;
550 tmp = xmalloc (sizeof (LBUFFER));
551
552 /* Input is always read into a fresh buffer. */
553 while (1)
554 {
555 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
556 if (n_read == 0 || n_read == SAFE_READ_ERROR)
557 break;
558 tmp->nbytes = n_read;
559 *read_pos += n_read;
560 tmp->nlines = 0;
561 tmp->next = NULL;
562
563 /* Count the number of newlines just read. */
564 {
565 char const *buffer_end = tmp->buffer + n_read;
566 char const *p = tmp->buffer;
567 while ((p = memchr (p, '\n', buffer_end - p)))
568 {
569 ++p;
570 ++tmp->nlines;
571 }
572 }
573 total_lines += tmp->nlines;
574
575 /* If there is enough room in the last buffer read, just append the new
576 one to it. This is because when reading from a pipe, `n_read' can
577 often be very small. */
578 if (tmp->nbytes + last->nbytes < BUFSIZ)
579 {
580 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
581 last->nbytes += tmp->nbytes;
582 last->nlines += tmp->nlines;
583 }
584 else
585 {
586 /* If there's not enough room, link the new buffer onto the end of
587 the list, then either free up the oldest buffer for the next
588 read if that would leave enough lines, or else malloc a new one.
589 Some compaction mechanism is possible but probably not
590 worthwhile. */
591 last = last->next = tmp;
592 if (total_lines - first->nlines > n_lines)
593 {
594 tmp = first;
595 total_lines -= first->nlines;
596 first = first->next;
597 }
598 else
599 tmp = xmalloc (sizeof (LBUFFER));
600 }
601 }
602
603 free (tmp);
604
605 if (n_read == SAFE_READ_ERROR)
606 {
607 error (0, errno, _("error reading %s"), quote (pretty_filename));
608 ok = false;
609 goto free_lbuffers;
610 }
611
612 /* If the file is empty, then bail out. */
613 if (last->nbytes == 0)
614 goto free_lbuffers;
615
616 /* This prevents a core dump when the pipe contains no newlines. */
617 if (n_lines == 0)
618 goto free_lbuffers;
619
620 /* Count the incomplete line on files that don't end with a newline. */
621 if (last->buffer[last->nbytes - 1] != '\n')
622 {
623 ++last->nlines;
624 ++total_lines;
625 }
626
627 /* Run through the list, printing lines. First, skip over unneeded
628 buffers. */
629 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
630 total_lines -= tmp->nlines;
631
632 /* Find the correct beginning, then print the rest of the file. */
633 {
634 char const *beg = tmp->buffer;
635 char const *buffer_end = tmp->buffer + tmp->nbytes;
636 if (total_lines > n_lines)
637 {
638 /* Skip `total_lines' - `n_lines' newlines. We made sure that
639 `total_lines' - `n_lines' <= `tmp->nlines'. */
640 size_t j;
641 for (j = total_lines - n_lines; j; --j)
642 {
643 beg = memchr (beg, '\n', buffer_end - beg);
644 assert (beg);
645 ++beg;
646 }
647 }
648
649 xwrite_stdout (beg, buffer_end - beg);
650 }
651
652 for (tmp = tmp->next; tmp; tmp = tmp->next)
653 xwrite_stdout (tmp->buffer, tmp->nbytes);
654
655free_lbuffers:
656 while (first)
657 {
658 tmp = first->next;
659 free (first);
660 first = tmp;
661 }
662 return ok;
663}
664
665/* Print the last N_BYTES characters from the end of pipe FD.
666 This is a stripped down version of pipe_lines.
667 Return true if successful. */
668
669static bool
670pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
671 uintmax_t *read_pos)
672{
673 struct charbuffer
674 {
675 char buffer[BUFSIZ];
676 size_t nbytes;
677 struct charbuffer *next;
678 };
679 typedef struct charbuffer CBUFFER;
680 CBUFFER *first, *last, *tmp;
681 size_t i; /* Index into buffers. */
682 size_t total_bytes = 0; /* Total characters in all buffers. */
683 bool ok = true;
684 size_t n_read;
685
686 first = last = xmalloc (sizeof (CBUFFER));
687 first->nbytes = 0;
688 first->next = NULL;
689 tmp = xmalloc (sizeof (CBUFFER));
690
691 /* Input is always read into a fresh buffer. */
692 while (1)
693 {
694 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
695 if (n_read == 0 || n_read == SAFE_READ_ERROR)
696 break;
697 *read_pos += n_read;
698 tmp->nbytes = n_read;
699 tmp->next = NULL;
700
701 total_bytes += tmp->nbytes;
702 /* If there is enough room in the last buffer read, just append the new
703 one to it. This is because when reading from a pipe, `nbytes' can
704 often be very small. */
705 if (tmp->nbytes + last->nbytes < BUFSIZ)
706 {
707 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
708 last->nbytes += tmp->nbytes;
709 }
710 else
711 {
712 /* If there's not enough room, link the new buffer onto the end of
713 the list, then either free up the oldest buffer for the next
714 read if that would leave enough characters, or else malloc a new
715 one. Some compaction mechanism is possible but probably not
716 worthwhile. */
717 last = last->next = tmp;
718 if (total_bytes - first->nbytes > n_bytes)
719 {
720 tmp = first;
721 total_bytes -= first->nbytes;
722 first = first->next;
723 }
724 else
725 {
726 tmp = xmalloc (sizeof (CBUFFER));
727 }
728 }
729 }
730
731 free (tmp);
732
733 if (n_read == SAFE_READ_ERROR)
734 {
735 error (0, errno, _("error reading %s"), quote (pretty_filename));
736 ok = false;
737 goto free_cbuffers;
738 }
739
740 /* Run through the list, printing characters. First, skip over unneeded
741 buffers. */
742 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
743 total_bytes -= tmp->nbytes;
744
745 /* Find the correct beginning, then print the rest of the file.
746 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
747 if (total_bytes > n_bytes)
748 i = total_bytes - n_bytes;
749 else
750 i = 0;
751 xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
752
753 for (tmp = tmp->next; tmp; tmp = tmp->next)
754 xwrite_stdout (tmp->buffer, tmp->nbytes);
755
756free_cbuffers:
757 while (first)
758 {
759 tmp = first->next;
760 free (first);
761 first = tmp;
762 }
763 return ok;
764}
765
766/* Skip N_BYTES characters from the start of pipe FD, and print
767 any extra characters that were read beyond that.
768 Return 1 on error, 0 if ok, -1 if EOF. */
769
770static int
771start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
772 uintmax_t *read_pos)
773{
774 char buffer[BUFSIZ];
775
776 while (0 < n_bytes)
777 {
778 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
779 if (bytes_read == 0)
780 return -1;
781 if (bytes_read == SAFE_READ_ERROR)
782 {
783 error (0, errno, _("error reading %s"), quote (pretty_filename));
784 return 1;
785 }
786 read_pos += bytes_read;
787 if (bytes_read <= n_bytes)
788 n_bytes -= bytes_read;
789 else
790 {
791 size_t n_remaining = bytes_read - n_bytes;
792 if (n_remaining)
793 xwrite_stdout (&buffer[n_bytes], n_remaining);
794 break;
795 }
796 }
797
798 return 0;
799}
800
801/* Skip N_LINES lines at the start of file or pipe FD, and print
802 any extra characters that were read beyond that.
803 Return 1 on error, 0 if ok, -1 if EOF. */
804
805static int
806start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
807 uintmax_t *read_pos)
808{
809 if (n_lines == 0)
810 return 0;
811
812 while (1)
813 {
814 char buffer[BUFSIZ];
815 char *p = buffer;
816 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
817 char *buffer_end = buffer + bytes_read;
818 if (bytes_read == 0) /* EOF */
819 return -1;
820 if (bytes_read == SAFE_READ_ERROR) /* error */
821 {
822 error (0, errno, _("error reading %s"), quote (pretty_filename));
823 return 1;
824 }
825
826 *read_pos += bytes_read;
827
828 while ((p = memchr (p, '\n', buffer_end - p)))
829 {
830 ++p;
831 if (--n_lines == 0)
832 {
833 if (p < buffer_end)
834 xwrite_stdout (p, buffer_end - p);
835 return 0;
836 }
837 }
838 }
839}
840
841/* FIXME: describe */
842
843static void
844recheck (struct File_spec *f, bool blocking)
845{
846 /* open/fstat the file and announce if dev/ino have changed */
847 struct stat new_stats;
848 bool ok = true;
849 bool is_stdin = (STREQ (f->name, "-"));
850 bool was_tailable = f->tailable;
851 int prev_errnum = f->errnum;
852 bool new_file;
853 int fd = (is_stdin
854 ? STDIN_FILENO
855 : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
856
857 assert (valid_file_spec (f));
858
859 /* If the open fails because the file doesn't exist,
860 then mark the file as not tailable. */
861 f->tailable = !(reopen_inaccessible_files && fd == -1);
862
863 if (fd == -1 || fstat (fd, &new_stats) < 0)
864 {
865 ok = false;
866 f->errnum = errno;
867 if (!f->tailable)
868 {
869 if (was_tailable)
870 {
871 /* FIXME-maybe: detect the case in which the file first becomes
872 unreadable (perms), and later becomes readable again and can
873 be seen to be the same file (dev/ino). Otherwise, tail prints
874 the entire contents of the file when it becomes readable. */
875 error (0, f->errnum, _("%s has become inaccessible"),
876 quote (pretty_name (f)));
877 }
878 else
879 {
880 /* say nothing... it's still not tailable */
881 }
882 }
883 else if (prev_errnum != errno)
884 {
885 error (0, errno, "%s", pretty_name (f));
886 }
887 }
888 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
889 {
890 ok = false;
891 f->errnum = -1;
892 error (0, 0, _("%s has been replaced with an untailable file;\
893 giving up on this name"),
894 quote (pretty_name (f)));
895 f->ignore = true;
896 }
897 else
898 {
899 f->errnum = 0;
900 }
901
902 new_file = false;
903 if (!ok)
904 {
905 close_fd (fd, pretty_name (f));
906 close_fd (f->fd, pretty_name (f));
907 f->fd = -1;
908 }
909 else if (prev_errnum && prev_errnum != ENOENT)
910 {
911 new_file = true;
912 assert (f->fd == -1);
913 error (0, 0, _("%s has become accessible"), quote (pretty_name (f)));
914 }
915 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
916 {
917 new_file = true;
918 if (f->fd == -1)
919 {
920 error (0, 0,
921 _("%s has appeared; following end of new file"),
922 quote (pretty_name (f)));
923 }
924 else
925 {
926 /* Close the old one. */
927 close_fd (f->fd, pretty_name (f));
928
929 /* File has been replaced (e.g., via log rotation) --
930 tail the new one. */
931 error (0, 0,
932 _("%s has been replaced; following end of new file"),
933 quote (pretty_name (f)));
934 }
935 }
936 else
937 {
938 if (f->fd == -1)
939 {
940 /* This happens when one iteration finds the file missing,
941 then the preceding <dev,inode> pair is reused as the
942 file is recreated. */
943 new_file = true;
944 }
945 else
946 {
947 close_fd (fd, pretty_name (f));
948 }
949 }
950
951 if (new_file)
952 {
953 /* Start at the beginning of the file. */
954 record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
955 xlseek (fd, 0, SEEK_SET, pretty_name (f));
956 }
957}
958
959/* Return true if any of the N_FILES files in F are live, i.e., have
960 open file descriptors. */
961
962static bool
963any_live_files (const struct File_spec *f, int n_files)
964{
965 int i;
966
967 for (i = 0; i < n_files; i++)
968 if (0 <= f[i].fd)
969 return true;
970 return false;
971}
972
973/* Tail NFILES files forever, or until killed.
974 The pertinent information for each file is stored in an entry of F.
975 Loop over each of them, doing an fstat to see if they have changed size,
976 and an occasional open/fstat to see if any dev/ino pair has changed.
977 If none of them have changed size in one iteration, sleep for a
978 while and try again. Continue until the user interrupts us. */
979
980static void
981tail_forever (struct File_spec *f, int nfiles, double sleep_interval)
982{
983 /* Use blocking I/O as an optimization, when it's easy. */
984 bool blocking = (pid == 0 && follow_mode == Follow_descriptor
985 && nfiles == 1 && ! S_ISREG (f[0].mode));
986 int last;
987 bool writer_is_dead = false;
988
989 last = nfiles - 1;
990
991 while (1)
992 {
993 int i;
994 bool any_input = false;
995
996 for (i = 0; i < nfiles; i++)
997 {
998 int fd;
999 char const *name;
1000 mode_t mode;
1001 struct stat stats;
1002 uintmax_t bytes_read;
1003
1004 if (f[i].ignore)
1005 continue;
1006
1007 if (f[i].fd < 0)
1008 {
1009 recheck (&f[i], blocking);
1010 continue;
1011 }
1012
1013 fd = f[i].fd;
1014 name = pretty_name (&f[i]);
1015 mode = f[i].mode;
1016
1017 if (f[i].blocking != blocking)
1018 {
1019 int old_flags = fcntl (fd, F_GETFL);
1020 int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
1021 if (old_flags < 0
1022 || (new_flags != old_flags
1023 && fcntl (fd, F_SETFL, new_flags) == -1))
1024 {
1025 /* Don't update f[i].blocking if fcntl fails. */
1026 if (S_ISREG (f[i].mode) && errno == EPERM)
1027 {
1028 /* This happens when using tail -f on a file with
1029 the append-only attribute. */
1030 }
1031 else
1032 error (EXIT_FAILURE, errno,
1033 _("%s: cannot change nonblocking mode"), name);
1034 }
1035 else
1036 f[i].blocking = blocking;
1037 }
1038
1039 if (!f[i].blocking)
1040 {
1041 if (fstat (fd, &stats) != 0)
1042 {
1043 f[i].fd = -1;
1044 f[i].errnum = errno;
1045 error (0, errno, "%s", name);
1046 continue;
1047 }
1048
1049 if (f[i].mode == stats.st_mode
1050 && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
1051 && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
1052 {
1053 if ((max_n_unchanged_stats_between_opens
1054 <= f[i].n_unchanged_stats++)
1055 && follow_mode == Follow_name)
1056 {
1057 recheck (&f[i], f[i].blocking);
1058 f[i].n_unchanged_stats = 0;
1059 }
1060 continue;
1061 }
1062
1063 /* This file has changed. Print out what we can, and
1064 then keep looping. */
1065
1066 f[i].mtime = get_stat_mtime (&stats);
1067 f[i].mode = stats.st_mode;
1068
1069 /* reset counter */
1070 f[i].n_unchanged_stats = 0;
1071
1072 if (S_ISREG (mode) && stats.st_size < f[i].size)
1073 {
1074 error (0, 0, _("%s: file truncated"), name);
1075 last = i;
1076 xlseek (fd, stats.st_size, SEEK_SET, name);
1077 f[i].size = stats.st_size;
1078 continue;
1079 }
1080
1081 if (i != last)
1082 {
1083 if (print_headers)
1084 write_header (name);
1085 last = i;
1086 }
1087 }
1088
1089 bytes_read = dump_remainder (name, fd,
1090 (f[i].blocking
1091 ? COPY_A_BUFFER : COPY_TO_EOF));
1092 any_input |= (bytes_read != 0);
1093 f[i].size += bytes_read;
1094 }
1095
1096 if (! any_live_files (f, nfiles) && ! reopen_inaccessible_files)
1097 {
1098 error (0, 0, _("no files remaining"));
1099 break;
1100 }
1101
1102 if ((!any_input | blocking) && fflush (stdout) != 0)
1103 error (EXIT_FAILURE, errno, _("write error"));
1104
1105 /* If nothing was read, sleep and/or check for dead writers. */
1106 if (!any_input)
1107 {
1108 if (writer_is_dead)
1109 break;
1110
1111 if (xnanosleep (sleep_interval))
1112 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1113
1114 /* Once the writer is dead, read the files once more to
1115 avoid a race condition. */
1116 writer_is_dead = (pid != 0
1117 && kill (pid, 0) != 0
1118 /* Handle the case in which you cannot send a
1119 signal to the writer, so kill fails and sets
1120 errno to EPERM. */
1121 && errno != EPERM);
1122 }
1123 }
1124}
1125
1126/* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1127 Return true if successful. */
1128
1129static bool
1130tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1131 uintmax_t *read_pos)
1132{
1133 struct stat stats;
1134
1135 if (fstat (fd, &stats))
1136 {
1137 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1138 return false;
1139 }
1140
1141 if (from_start)
1142 {
1143 if ( ! presume_input_pipe
1144 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1145 {
1146 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1147 *read_pos += n_bytes;
1148 }
1149 else
1150 {
1151 int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
1152 if (t)
1153 return t < 0;
1154 }
1155 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1156 }
1157 else
1158 {
1159 if ( ! presume_input_pipe
1160 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1161 {
1162 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1163 off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename);
1164 off_t diff = end_pos - current_pos;
1165 /* Be careful here. The current position may actually be
1166 beyond the end of the file. */
1167 off_t bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff;
1168 off_t nb = n_bytes;
1169
1170 if (bytes_remaining <= nb)
1171 {
1172 /* From the current position to end of file, there are no
1173 more bytes than have been requested. So reposition the
1174 file pointer to the incoming current position and print
1175 everything after that. */
1176 *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1177 }
1178 else
1179 {
1180 /* There are more bytes remaining than were requested.
1181 Back up. */
1182 *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename);
1183 }
1184 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1185 }
1186 else
1187 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1188 }
1189 return true;
1190}
1191
1192/* Output the last N_LINES lines of file FILENAME open for reading in FD.
1193 Return true if successful. */
1194
1195static bool
1196tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1197 uintmax_t *read_pos)
1198{
1199 struct stat stats;
1200
1201 if (fstat (fd, &stats))
1202 {
1203 error (0, errno, _("cannot fstat %s"), quote (pretty_filename));
1204 return false;
1205 }
1206
1207 if (from_start)
1208 {
1209 int t = start_lines (pretty_filename, fd, n_lines, read_pos);
1210 if (t)
1211 return t < 0;
1212 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1213 }
1214 else
1215 {
1216 off_t start_pos = -1;
1217 off_t end_pos;
1218
1219 /* Use file_lines only if FD refers to a regular file for
1220 which lseek (... SEEK_END) works. */
1221 if ( ! presume_input_pipe
1222 && S_ISREG (stats.st_mode)
1223 && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
1224 && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
1225 {
1226 *read_pos = end_pos;
1227 if (end_pos != 0
1228 && ! file_lines (pretty_filename, fd, n_lines,
1229 start_pos, end_pos, read_pos))
1230 return false;
1231 }
1232 else
1233 {
1234 /* Under very unlikely circumstances, it is possible to reach
1235 this point after positioning the file pointer to end of file
1236 via the `lseek (...SEEK_END)' above. In that case, reposition
1237 the file pointer back to start_pos before calling pipe_lines. */
1238 if (start_pos != -1)
1239 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1240
1241 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1242 }
1243 }
1244 return true;
1245}
1246
1247/* Display the last N_UNITS units of file FILENAME, open for reading
1248 via FD. Set *READ_POS to the position of the input stream pointer.
1249 *READ_POS is usually the number of bytes read and corresponds to an
1250 offset from the beginning of a file. However, it may be larger than
1251 OFF_T_MAX (as for an input pipe), and may also be larger than the
1252 number of bytes read (when an input pointer is initially not at
1253 beginning of file), and may be far greater than the number of bytes
1254 actually read for an input file that is seekable.
1255 Return true if successful. */
1256
1257static bool
1258tail (const char *filename, int fd, uintmax_t n_units,
1259 uintmax_t *read_pos)
1260{
1261 *read_pos = 0;
1262 if (count_lines)
1263 return tail_lines (filename, fd, n_units, read_pos);
1264 else
1265 return tail_bytes (filename, fd, n_units, read_pos);
1266}
1267
1268/* Display the last N_UNITS units of the file described by F.
1269 Return true if successful. */
1270
1271static bool
1272tail_file (struct File_spec *f, uintmax_t n_units)
1273{
1274 int fd;
1275 bool ok;
1276
1277 bool is_stdin = (STREQ (f->name, "-"));
1278
1279 if (is_stdin)
1280 {
1281 have_read_stdin = true;
1282 fd = STDIN_FILENO;
1283 if (O_BINARY && ! isatty (STDIN_FILENO))
1284 freopen (NULL, "rb", stdin);
1285 }
1286 else
1287 fd = open (f->name, O_RDONLY | O_BINARY);
1288
1289 f->tailable = !(reopen_inaccessible_files && fd == -1);
1290
1291 if (fd == -1)
1292 {
1293 if (forever)
1294 {
1295 f->fd = -1;
1296 f->errnum = errno;
1297 f->ignore = false;
1298 f->ino = 0;
1299 f->dev = 0;
1300 }
1301 error (0, errno, _("cannot open %s for reading"),
1302 quote (pretty_name (f)));
1303 ok = false;
1304 }
1305 else
1306 {
1307 uintmax_t read_pos;
1308
1309 if (print_headers)
1310 write_header (pretty_name (f));
1311 ok = tail (pretty_name (f), fd, n_units, &read_pos);
1312 if (forever)
1313 {
1314 struct stat stats;
1315
1316#if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT
1317 /* Before the tail function provided `read_pos', there was
1318 a race condition described in the URL below. This sleep
1319 call made the window big enough to exercise the problem. */
1320 sleep (1);
1321#endif
1322 f->errnum = ok - 1;
1323 if (fstat (fd, &stats) < 0)
1324 {
1325 ok = false;
1326 f->errnum = errno;
1327 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1328 }
1329 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1330 {
1331 error (0, 0, _("%s: cannot follow end of this type of file;\
1332 giving up on this name"),
1333 pretty_name (f));
1334 ok = false;
1335 f->errnum = -1;
1336 f->ignore = true;
1337 }
1338
1339 if (!ok)
1340 {
1341 close_fd (fd, pretty_name (f));
1342 f->fd = -1;
1343 }
1344 else
1345 {
1346 /* Note: we must use read_pos here, not stats.st_size,
1347 to avoid a race condition described by Ken Raeburn:
1348 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1349 record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
1350 }
1351 }
1352 else
1353 {
1354 if (!is_stdin && close (fd))
1355 {
1356 error (0, errno, _("error reading %s"), quote (pretty_name (f)));
1357 ok = false;
1358 }
1359 }
1360 }
1361
1362 return ok;
1363}
1364
1365/* If obsolete usage is allowed, and the command line arguments are of
1366 the obsolete form and the option string is well-formed, set
1367 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1368 return true. If the command line arguments are obviously incorrect
1369 (e.g., because obsolete usage is not allowed and the arguments are
1370 incorrect for non-obsolete usage), report an error and exit.
1371 Otherwise, return false and don't modify any parameter or global
1372 variable. */
1373
1374static bool
1375parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
1376{
1377 const char *p;
1378 const char *n_string;
1379 const char *n_string_end;
1380 bool obsolete_usage;
1381 int default_count = DEFAULT_N_LINES;
1382 bool t_from_start;
1383 bool t_count_lines = true;
1384 bool t_forever = false;
1385
1386 /* With the obsolete form, there is one option string and at most
1387 one file argument. Watch out for "-" and "--", though. */
1388 if (! (argc == 2
1389 || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
1390 || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
1391 return false;
1392
1393 obsolete_usage = (posix2_version () < 200112);
1394 p = argv[1];
1395
1396 switch (*p++)
1397 {
1398 default:
1399 return false;
1400
1401 case '+':
1402 /* Leading "+" is a file name in the non-obsolete form. */
1403 if (!obsolete_usage)
1404 return false;
1405
1406 t_from_start = true;
1407 break;
1408
1409 case '-':
1410 /* In the non-obsolete form, "-" is standard input and "-c"
1411 requires an option-argument. The obsolete multidigit options
1412 are supported as a GNU extension even when conforming to
1413 POSIX 1003.1-2001, so don't complain about them. */
1414 if (!obsolete_usage && !p[p[0] == 'c'])
1415 return false;
1416
1417 t_from_start = false;
1418 break;
1419 }
1420
1421 n_string = p;
1422 while (ISDIGIT (*p))
1423 p++;
1424 n_string_end = p;
1425
1426 switch (*p)
1427 {
1428 case 'b': default_count *= 512; /* Fall through. */
1429 case 'c': t_count_lines = false; /* Fall through. */
1430 case 'l': p++; break;
1431 }
1432
1433 if (*p == 'f')
1434 {
1435 t_forever = true;
1436 ++p;
1437 }
1438
1439 if (*p)
1440 return false;
1441
1442 if (n_string == n_string_end)
1443 *n_units = default_count;
1444 else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
1445 & ~LONGINT_INVALID_SUFFIX_CHAR)
1446 != LONGINT_OK)
1447 error (EXIT_FAILURE, 0, _("number in %s is too large"), quote (argv[1]));
1448
1449 /* Set globals. */
1450 from_start = t_from_start;
1451 count_lines = t_count_lines;
1452 forever = t_forever;
1453
1454 return true;
1455}
1456
1457static void
1458parse_options (int argc, char **argv,
1459 uintmax_t *n_units, enum header_mode *header_mode,
1460 double *sleep_interval)
1461{
1462 int c;
1463
1464 while ((c = getopt_long (argc, argv, "c:n:fFqs:v", long_options, NULL))
1465 != -1)
1466 {
1467 switch (c)
1468 {
1469 case 'F':
1470 forever = true;
1471 follow_mode = Follow_name;
1472 reopen_inaccessible_files = true;
1473 break;
1474
1475 case 'c':
1476 case 'n':
1477 count_lines = (c == 'n');
1478 if (*optarg == '+')
1479 from_start = true;
1480 else if (*optarg == '-')
1481 ++optarg;
1482
1483 {
1484 strtol_error s_err;
1485 s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkm");
1486 if (s_err != LONGINT_OK)
1487 {
1488 error (EXIT_FAILURE, 0, "%s: %s", optarg,
1489 (c == 'n'
1490 ? _("invalid number of lines")
1491 : _("invalid number of bytes")));
1492 }
1493 }
1494 break;
1495
1496 case 'f':
1497 case LONG_FOLLOW_OPTION:
1498 forever = true;
1499 if (optarg == NULL)
1500 follow_mode = DEFAULT_FOLLOW_MODE;
1501 else
1502 follow_mode = XARGMATCH ("--follow", optarg,
1503 follow_mode_string, follow_mode_map);
1504 break;
1505
1506 case RETRY_OPTION:
1507 reopen_inaccessible_files = true;
1508 break;
1509
1510 case MAX_UNCHANGED_STATS_OPTION:
1511 /* --max-unchanged-stats=N */
1512 if (xstrtoumax (optarg, NULL, 10,
1513 &max_n_unchanged_stats_between_opens,
1514 "")
1515 != LONGINT_OK)
1516 {
1517 error (EXIT_FAILURE, 0,
1518 _("%s: invalid maximum number of unchanged stats between opens"),
1519 optarg);
1520 }
1521 break;
1522
1523 case PID_OPTION:
1524 {
1525 strtol_error s_err;
1526 unsigned long int tmp_ulong;
1527 s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, "");
1528 if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX)
1529 {
1530 error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg);
1531 }
1532 pid = tmp_ulong;
1533 }
1534 break;
1535
1536 case PRESUME_INPUT_PIPE_OPTION:
1537 presume_input_pipe = true;
1538 break;
1539
1540 case 'q':
1541 *header_mode = never;
1542 break;
1543
1544 case 's':
1545 {
1546 double s;
1547 if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
1548 error (EXIT_FAILURE, 0,
1549 _("%s: invalid number of seconds"), optarg);
1550 *sleep_interval = s;
1551 }
1552 break;
1553
1554 case 'v':
1555 *header_mode = always;
1556 break;
1557
1558 case_GETOPT_HELP_CHAR;
1559
1560 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1561
1562 default:
1563 usage (EXIT_FAILURE);
1564 }
1565 }
1566
1567 if (reopen_inaccessible_files && follow_mode != Follow_name)
1568 error (0, 0, _("warning: --retry is useful only when following by name"));
1569
1570 if (pid && !forever)
1571 error (0, 0,
1572 _("warning: PID ignored; --pid=PID is useful only when following"));
1573 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
1574 {
1575 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1576 pid = 0;
1577 }
1578}
1579
1580int
1581main (int argc, char **argv)
1582{
1583 enum header_mode header_mode = multiple_files;
1584 bool ok = true;
1585 /* If from_start, the number of items to skip before printing; otherwise,
1586 the number of items at the end of the file to print. Although the type
1587 is signed, the value is never negative. */
1588 uintmax_t n_units = DEFAULT_N_LINES;
1589 int n_files;
1590 char **file;
1591 struct File_spec *F;
1592 int i;
1593 bool obsolete_option;
1594
1595 /* The number of seconds to sleep between iterations.
1596 During one iteration, every file name or descriptor is checked to
1597 see if it has changed. */
1598 double sleep_interval = 1.0;
1599
1600 initialize_main (&argc, &argv);
1601 program_name = argv[0];
1602 setlocale (LC_ALL, "");
1603 bindtextdomain (PACKAGE, LOCALEDIR);
1604 textdomain (PACKAGE);
1605
1606 atexit (close_stdout);
1607
1608 have_read_stdin = false;
1609
1610 count_lines = true;
1611 forever = from_start = print_headers = false;
1612 obsolete_option = parse_obsolete_option (argc, argv, &n_units);
1613 argc -= obsolete_option;
1614 argv += obsolete_option;
1615 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
1616
1617 /* To start printing with item N_UNITS from the start of the file, skip
1618 N_UNITS - 1 items. `tail -n +0' is actually meaningless, but for Unix
1619 compatibility it's treated the same as `tail -n +1'. */
1620 if (from_start)
1621 {
1622 if (n_units)
1623 --n_units;
1624 }
1625
1626 if (optind < argc)
1627 {
1628 n_files = argc - optind;
1629 file = argv + optind;
1630 }
1631 else
1632 {
1633 static char *dummy_stdin = "-";
1634 n_files = 1;
1635 file = &dummy_stdin;
1636
1637 /* POSIX says that -f is ignored if no file operand is specified
1638 and standard input is a pipe. */
1639 if (forever)
1640 {
1641 struct stat stats;
1642 if (fstat (STDIN_FILENO, &stats) == 0
1643 && IS_PIPE_LIKE_FILE_TYPE (stats.st_mode))
1644 forever = false;
1645 }
1646 }
1647
1648 {
1649 bool found_hyphen = false;
1650
1651 for (i = 0; i < n_files; i++)
1652 if (STREQ (file[i], "-"))
1653 found_hyphen = true;
1654
1655 /* When following by name, there must be a name. */
1656 if (found_hyphen && follow_mode == Follow_name)
1657 error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quote ("-"));
1658
1659 /* When following forever, warn if any file is `-'.
1660 This is only a warning, since tail's output (before a failing seek,
1661 and that from any non-stdin files) might still be useful. */
1662 if (forever && found_hyphen && isatty (STDIN_FILENO))
1663 error (0, 0, _("warning: following standard input"
1664 " indefinitely is ineffective"));
1665 }
1666
1667 F = xnmalloc (n_files, sizeof *F);
1668 for (i = 0; i < n_files; i++)
1669 F[i].name = file[i];
1670
1671 if (header_mode == always
1672 || (header_mode == multiple_files && n_files > 1))
1673 print_headers = true;
1674
1675 if (O_BINARY && ! isatty (STDOUT_FILENO))
1676 freopen (NULL, "wb", stdout);
1677
1678 for (i = 0; i < n_files; i++)
1679 ok &= tail_file (&F[i], n_units);
1680
1681 if (forever)
1682 tail_forever (F, n_files, sleep_interval);
1683
1684 if (have_read_stdin && close (STDIN_FILENO) < 0)
1685 error (EXIT_FAILURE, errno, "-");
1686 exit (ok ? EXIT_SUCCESS : EXIT_FAILURE);
1687}
Note: See TracBrowser for help on using the repository browser.