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