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