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