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