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