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