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