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