1 /* tail -- output the last part of file(s)
2 Copyright (C) 89, 90, 91, 1995-1999 Free Software Foundation, Inc.
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)
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.
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. */
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
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>. */
31 #include <sys/types.h>
37 #include "safe-read.h"
40 /* The official name of this program (e.g., no `g' prefix). */
41 #define PROGRAM_NAME "tail"
44 "Paul Rubin, David MacKenzie, Ian Lance Taylor, and Jim Meyering"
47 # define OFF_T_MIN TYPE_MINIMUM (off_t)
51 # define OFF_T_MAX TYPE_MAXIMUM (off_t)
55 /* Some systems don't have ENOSYS -- this should be a big enough
56 value that no valid errno value will match it. */
60 /* Number of items to tail. */
61 #define DEFAULT_N_LINES 10
63 /* Size of atomic reads. */
65 # define BUFSIZ (512 * 8)
68 /* A special value for dump_remainder's N_BYTES parameter. */
69 #define COPY_TO_EOF OFF_T_MAX
71 /* FIXME: make Follow_name the default? */
72 #define DEFAULT_FOLLOW_MODE Follow_descriptor
76 /* Follow the name of each file: if the file is renamed, try to reopen
77 that name and track the end of the new file if/when it's recreated.
78 This is useful for tracking logs that are occasionally rotated. */
81 /* Follow each descriptor obtained upon opening a file.
82 That means we'll continue to follow the end of a file even after
83 it has been renamed or unlinked. */
87 static char const *const follow_mode_string
[] =
89 "descriptor", "name", 0
92 static enum Follow_mode
const follow_mode_map
[] =
94 Follow_descriptor
, Follow_name
,
99 /* The actual file name, or "-" for stdin. */
102 /* File descriptor on which the file is open; -1 if it's not open. */
105 /* The size of the file the last time we checked. */
108 /* The device and inode of the file the last time we checked. */
112 /* See description of DEFAULT_MAX_N_... below. */
113 unsigned int n_unchanged_stats
;
115 /* See description of DEFAULT_MAX_N_... below. */
116 unsigned int n_consecutive_size_changes
;
118 /* A file is tailable if it is a regular file or a fifo and it is
122 /* The value of errno seen last time we checked this file. */
127 /* Keep trying to open a file even if it is inaccessible when tail starts
128 or if it becomes inaccessible later -- useful only with -f. */
129 static int reopen_inaccessible_files
;
131 /* If nonzero, interpret the numeric argument as the number of lines.
132 Otherwise, interpret it as the number of bytes. */
133 static int count_lines
;
135 /* Whether we follow the name of each file or the file descriptor
136 that is initially associated with each name. */
137 static enum Follow_mode follow_mode
= Follow_descriptor
;
139 /* If nonzero, read from the ends of all specified files until killed. */
142 /* If nonzero, count from start of file instead of end. */
143 static int from_start
;
145 /* If nonzero, print filename headers. */
146 static int print_headers
;
148 /* When to print the filename banners. */
151 multiple_files
, always
, never
154 /* When tailing a file by name, if there have been this many consecutive
155 iterations for which the size has remained the same, then open/fstat
156 the file to determine if that file name is still associated with the
157 same device/inode-number pair as before. This option is meaningful only
158 when following by name. --max-unchanged-stats=N */
159 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
160 static unsigned long max_n_unchanged_stats_between_opens
=
161 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
;
163 /* This variable is used to ensure that a file that is unlinked or moved
164 aside, yet always growing will be recognized as having been renamed.
165 After detecting this many consecutive size changes for a file, open/fstat
166 the file to determine if that file name is still associated with the
167 same device/inode-number pair as before. This option is meaningful only
168 when following by name. --max-consecutive-size-changes=N */
169 #define DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES 200
170 static unsigned long max_n_consecutive_size_changes_between_opens
=
171 DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES
;
173 /* The name this program was run with. */
176 /* The number of seconds to sleep between iterations.
177 During one iteration, every file name or descriptor is checked to
178 see if it has changed. */
179 /* FIXME: allow fractional seconds */
180 static unsigned int sleep_interval
= 1;
182 /* The process ID of the process (presumably on the current host)
183 that is writing to all followed files. */
186 /* Nonzero if we have ever read standard input. */
187 static int have_read_stdin
;
189 /* For long options that have no equivalent short option, use a
190 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
193 RETRY_OPTION
= CHAR_MAX
+ 1,
194 MAX_UNCHANGED_STATS_OPTION
,
195 MAX_CONSECUTIVE_SIZE_CHANGES_OPTION
,
200 static struct option
const long_options
[] =
202 /* --allow-missing is deprecated; use --retry instead
203 FIXME: remove it some day */
204 {"allow-missing", no_argument
, NULL
, RETRY_OPTION
},
205 {"bytes", required_argument
, NULL
, 'c'},
206 {"follow", optional_argument
, NULL
, LONG_FOLLOW_OPTION
},
207 {"lines", required_argument
, NULL
, 'n'},
208 {"max-unchanged-stats", required_argument
, NULL
, MAX_UNCHANGED_STATS_OPTION
},
209 {"max-consecutive-size-changes", required_argument
, NULL
,
210 MAX_CONSECUTIVE_SIZE_CHANGES_OPTION
},
211 {"pid", required_argument
, NULL
, PID_OPTION
},
212 {"quiet", no_argument
, NULL
, 'q'},
213 {"retry", no_argument
, NULL
, RETRY_OPTION
},
214 {"silent", no_argument
, NULL
, 'q'},
215 {"sleep-interval", required_argument
, NULL
, 's'},
216 {"verbose", no_argument
, NULL
, 'v'},
217 {GETOPT_HELP_OPTION_DECL
},
218 {GETOPT_VERSION_OPTION_DECL
},
226 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
231 Usage: %s [OPTION]... [FILE]...\n\
235 Print the last %d lines of each FILE to standard output.\n\
236 With more than one FILE, precede each with a header giving the file name.\n\
237 With no FILE, or when FILE is -, read standard input.\n\
239 --retry keep trying to open a file even if it is\n\
240 inaccessible when tail starts or if it becomes\n\
241 inaccessible later -- useful only with -f\n\
242 -c, --bytes=N output the last N bytes\n\
243 -f, --follow[={name|descriptor}] output appended data as the file grows;\n\
244 -f, --follow, and --follow=descriptor are\n\
246 -n, --lines=N output the last N lines, instead of the last %d\n\
247 --max-unchanged-stats=N see the texinfo documentation\n\
248 (the default is %d)\n\
249 --max-consecutive-size-changes=N see the texinfo documentation\n\
250 (the default is %d)\n\
251 --pid=PID with -f, terminate after process ID, PID dies\n\
252 -q, --quiet, --silent never output headers giving file names\n\
253 -s, --sleep-interval=S with -f, sleep S seconds between iterations\n\
254 -v, --verbose always output headers giving file names\n\
255 --help display this help and exit\n\
256 --version output version information and exit\n\
258 If the first character of N (the number of bytes or lines) is a `+',\n\
259 print beginning with the Nth item from the start of each file, otherwise,\n\
260 print the last N items in the file. N may have a multiplier suffix:\n\
261 b for 512, k for 1024, m for 1048576 (1 Meg). A first OPTION of -VALUE\n\
262 or +VALUE is treated like -n VALUE or -n +VALUE unless VALUE has one of\n\
263 the [bkm] suffix multipliers, in which case it is treated like -c VALUE\n\
266 With --follow (-f), tail defaults to following the file descriptor, which\n\
267 means that even if a tail'ed file is renamed, tail will continue to track\n\
268 its end. This default behavior is not desirable when you really want to\n\
269 track the actual name of the file, not the file descriptor (e.g., log\n\
270 rotation). Use --follow=name in that case. That causes tail to track the\n\
271 named file by reopening it periodically to see if it has been removed and\n\
272 recreated by some other program.\n\
275 DEFAULT_N_LINES
, DEFAULT_N_LINES
,
276 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
,
277 DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES
279 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
281 exit (status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);
285 valid_file_spec (struct File_spec
const *f
)
287 /* Exactly one of the following subexpressions must be true. */
288 return ((f
->fd
== -1) ^ (f
->errnum
== 0));
292 pretty_name (struct File_spec
const *f
)
294 return (STREQ (f
->name
, "-") ? "standard input" : f
->name
);
298 xwrite (int fd
, char *const buffer
, size_t n_bytes
)
300 assert (fd
== STDOUT_FILENO
);
301 assert (n_bytes
>= 0);
302 if (n_bytes
> 0 && fwrite (buffer
, 1, n_bytes
, stdout
) == 0)
303 error (EXIT_FAILURE
, errno
, _("write error"));
307 close_fd (int fd
, const char *filename
)
309 if (fd
!= -1 && fd
!= STDIN_FILENO
&& close (fd
))
311 error (0, errno
, _("closing %s (fd=%d)"), filename
, fd
);
316 write_header (const char *pretty_filename
, const char *comment
)
318 static int first_file
= 1;
320 printf ("%s==> %s%s%s <==\n", (first_file
? "" : "\n"), pretty_filename
,
321 (comment
? ": " : ""),
322 (comment
? comment
: ""));
326 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
327 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
328 Return the number of bytes read from the file. */
331 dump_remainder (const char *pretty_filename
, int fd
, off_t n_bytes
)
336 off_t n_remaining
= n_bytes
;
341 long n
= MIN (n_remaining
, (off_t
) BUFSIZ
);
342 bytes_read
= safe_read (fd
, buffer
, n
);
345 xwrite (STDOUT_FILENO
, buffer
, bytes_read
);
346 n_remaining
-= bytes_read
;
347 n_written
+= bytes_read
;
349 if (bytes_read
== -1)
350 error (EXIT_FAILURE
, errno
, "%s", pretty_filename
);
355 /* Print the last N_LINES lines from the end of file FD.
356 Go backward through the file, reading `BUFSIZ' bytes at a time (except
357 probably the first), until we hit the start of the file or have
358 read NUMBER newlines.
359 FILE_LENGTH is the length of the file (one more than the offset of the
360 last byte of the file).
361 Return 0 if successful, 1 if an error occurred. */
364 file_lines (const char *pretty_filename
, int fd
, long int n_lines
,
369 int i
; /* Index into `buffer' for scanning. */
370 off_t pos
= file_length
;
375 /* Set `bytes_read' to the size of the last, probably partial, buffer;
376 0 < `bytes_read' <= `BUFSIZ'. */
377 bytes_read
= pos
% BUFSIZ
;
380 /* Make `pos' a multiple of `BUFSIZ' (0 if the file is short), so that all
381 reads will be on block boundaries, which might increase efficiency. */
383 /* FIXME: check lseek return value */
384 lseek (fd
, pos
, SEEK_SET
);
385 bytes_read
= safe_read (fd
, buffer
, bytes_read
);
386 if (bytes_read
== -1)
388 error (0, errno
, "%s", pretty_filename
);
392 /* Count the incomplete line on files that don't end with a newline. */
393 if (bytes_read
&& buffer
[bytes_read
- 1] != '\n')
398 /* Scan backward, counting the newlines in this bufferfull. */
399 for (i
= bytes_read
- 1; i
>= 0; i
--)
401 /* Have we counted the requested number of newlines yet? */
402 if (buffer
[i
] == '\n' && n_lines
-- == 0)
404 /* If this newline wasn't the last character in the buffer,
405 print the text after it. */
406 if (i
!= bytes_read
- 1)
407 xwrite (STDOUT_FILENO
, &buffer
[i
+ 1], bytes_read
- (i
+ 1));
408 dump_remainder (pretty_filename
, fd
,
409 file_length
- (pos
+ bytes_read
));
413 /* Not enough newlines in that bufferfull. */
416 /* Not enough lines in the file; print the entire file. */
417 /* FIXME: check lseek return value */
418 lseek (fd
, (off_t
) 0, SEEK_SET
);
419 dump_remainder (pretty_filename
, fd
, file_length
);
423 /* FIXME: check lseek return value */
424 lseek (fd
, pos
, SEEK_SET
);
426 while ((bytes_read
= safe_read (fd
, buffer
, BUFSIZ
)) > 0);
428 if (bytes_read
== -1)
430 error (0, errno
, "%s", pretty_filename
);
437 /* Print the last N_LINES lines from the end of the standard input,
438 open for reading as pipe FD.
439 Buffer the text as a linked list of LBUFFERs, adding them as needed.
440 Return 0 if successful, 1 if an error occured. */
443 pipe_lines (const char *pretty_filename
, int fd
, long int n_lines
)
449 struct linebuffer
*next
;
451 typedef struct linebuffer LBUFFER
;
452 LBUFFER
*first
, *last
, *tmp
;
453 int i
; /* Index into buffers. */
454 int total_lines
= 0; /* Total number of newlines in all buffers. */
457 first
= last
= (LBUFFER
*) xmalloc (sizeof (LBUFFER
));
458 first
->nbytes
= first
->nlines
= 0;
460 tmp
= (LBUFFER
*) xmalloc (sizeof (LBUFFER
));
462 /* Input is always read into a fresh buffer. */
463 while ((tmp
->nbytes
= safe_read (fd
, tmp
->buffer
, BUFSIZ
)) > 0)
468 /* Count the number of newlines just read. */
469 for (i
= 0; i
< tmp
->nbytes
; i
++)
470 if (tmp
->buffer
[i
] == '\n')
472 total_lines
+= tmp
->nlines
;
474 /* If there is enough room in the last buffer read, just append the new
475 one to it. This is because when reading from a pipe, `nbytes' can
476 often be very small. */
477 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
479 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
480 last
->nbytes
+= tmp
->nbytes
;
481 last
->nlines
+= tmp
->nlines
;
485 /* If there's not enough room, link the new buffer onto the end of
486 the list, then either free up the oldest buffer for the next
487 read if that would leave enough lines, or else malloc a new one.
488 Some compaction mechanism is possible but probably not
490 last
= last
->next
= tmp
;
491 if (total_lines
- first
->nlines
> n_lines
)
494 total_lines
-= first
->nlines
;
498 tmp
= (LBUFFER
*) xmalloc (sizeof (LBUFFER
));
501 if (tmp
->nbytes
== -1)
503 error (0, errno
, "%s", pretty_filename
);
511 /* This prevents a core dump when the pipe contains no newlines. */
515 /* Count the incomplete line on files that don't end with a newline. */
516 if (last
->buffer
[last
->nbytes
- 1] != '\n')
522 /* Run through the list, printing lines. First, skip over unneeded
524 for (tmp
= first
; total_lines
- tmp
->nlines
> n_lines
; tmp
= tmp
->next
)
525 total_lines
-= tmp
->nlines
;
527 /* Find the correct beginning, then print the rest of the file. */
528 if (total_lines
> n_lines
)
532 /* Skip `total_lines' - `n_lines' newlines. We made sure that
533 `total_lines' - `n_lines' <= `tmp->nlines'. */
535 for (i
= total_lines
- n_lines
; i
; --i
)
536 while (*cp
++ != '\n')
538 i
= cp
- tmp
->buffer
;
542 xwrite (STDOUT_FILENO
, &tmp
->buffer
[i
], tmp
->nbytes
- i
);
544 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
545 xwrite (STDOUT_FILENO
, tmp
->buffer
, tmp
->nbytes
);
551 free ((char *) first
);
557 /* Print the last N_BYTES characters from the end of pipe FD.
558 This is a stripped down version of pipe_lines.
559 Return 0 if successful, 1 if an error occurred. */
562 pipe_bytes (const char *pretty_filename
, int fd
, off_t n_bytes
)
568 struct charbuffer
*next
;
570 typedef struct charbuffer CBUFFER
;
571 CBUFFER
*first
, *last
, *tmp
;
572 int i
; /* Index into buffers. */
573 int total_bytes
= 0; /* Total characters in all buffers. */
576 first
= last
= (CBUFFER
*) xmalloc (sizeof (CBUFFER
));
579 tmp
= (CBUFFER
*) xmalloc (sizeof (CBUFFER
));
581 /* Input is always read into a fresh buffer. */
582 while ((tmp
->nbytes
= safe_read (fd
, tmp
->buffer
, BUFSIZ
)) > 0)
586 total_bytes
+= tmp
->nbytes
;
587 /* If there is enough room in the last buffer read, just append the new
588 one to it. This is because when reading from a pipe, `nbytes' can
589 often be very small. */
590 if (tmp
->nbytes
+ last
->nbytes
< BUFSIZ
)
592 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
593 last
->nbytes
+= tmp
->nbytes
;
597 /* If there's not enough room, link the new buffer onto the end of
598 the list, then either free up the oldest buffer for the next
599 read if that would leave enough characters, or else malloc a new
600 one. Some compaction mechanism is possible but probably not
602 last
= last
->next
= tmp
;
603 if (total_bytes
- first
->nbytes
> n_bytes
)
606 total_bytes
-= first
->nbytes
;
611 tmp
= (CBUFFER
*) xmalloc (sizeof (CBUFFER
));
615 if (tmp
->nbytes
== -1)
617 error (0, errno
, "%s", pretty_filename
);
625 /* Run through the list, printing characters. First, skip over unneeded
627 for (tmp
= first
; total_bytes
- tmp
->nbytes
> n_bytes
; tmp
= tmp
->next
)
628 total_bytes
-= tmp
->nbytes
;
630 /* Find the correct beginning, then print the rest of the file.
631 We made sure that `total_bytes' - `n_bytes' <= `tmp->nbytes'. */
632 if (total_bytes
> n_bytes
)
633 i
= total_bytes
- n_bytes
;
636 xwrite (STDOUT_FILENO
, &tmp
->buffer
[i
], tmp
->nbytes
- i
);
638 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
639 xwrite (STDOUT_FILENO
, tmp
->buffer
, tmp
->nbytes
);
645 free ((char *) first
);
651 /* Skip N_BYTES characters from the start of pipe FD, and print
652 any extra characters that were read beyond that.
653 Return 1 on error, 0 if ok. */
656 start_bytes (const char *pretty_filename
, int fd
, off_t n_bytes
)
661 while (n_bytes
> 0 && (bytes_read
= safe_read (fd
, buffer
, BUFSIZ
)) > 0)
662 n_bytes
-= bytes_read
;
663 if (bytes_read
== -1)
665 error (0, errno
, "%s", pretty_filename
);
668 else if (n_bytes
< 0)
669 xwrite (STDOUT_FILENO
, &buffer
[bytes_read
+ n_bytes
], -n_bytes
);
673 /* Skip N_LINES lines at the start of file or pipe FD, and print
674 any extra characters that were read beyond that.
675 Return 1 on error, 0 if ok. */
678 start_lines (const char *pretty_filename
, int fd
, long int n_lines
)
682 int bytes_to_skip
= 0;
684 while (n_lines
&& (bytes_read
= safe_read (fd
, buffer
, BUFSIZ
)) > 0)
687 while (bytes_to_skip
< bytes_read
)
688 if (buffer
[bytes_to_skip
++] == '\n' && --n_lines
== 0)
691 if (bytes_read
== -1)
693 error (0, errno
, "%s", pretty_filename
);
696 else if (bytes_to_skip
< bytes_read
)
698 xwrite (STDOUT_FILENO
, &buffer
[bytes_to_skip
],
699 bytes_read
- bytes_to_skip
);
704 /* FIXME: describe */
707 recheck (struct File_spec
*f
)
709 /* open/fstat the file and announce if dev/ino have changed */
710 struct stat new_stats
;
713 int is_stdin
= (STREQ (f
->name
, "-"));
714 int was_tailable
= f
->tailable
;
715 int prev_errnum
= f
->errnum
;
718 assert (valid_file_spec (f
));
720 fd
= (is_stdin
? STDIN_FILENO
: open (f
->name
, O_RDONLY
));
722 /* If the open fails because the file doesn't exist,
723 then mark the file as not tailable. */
724 f
->tailable
= !(reopen_inaccessible_files
&& fd
== -1);
726 if (fd
== -1 || fstat (fd
, &new_stats
) < 0)
734 /* FIXME-maybe: detect the case in which the file first becomes
735 unreadable (perms), and later becomes readable again and can
736 be seen to be the same file (dev/ino). Otherwise, tail prints
737 the entire contents of the file when it becomes readable. */
738 error (0, f
->errnum
, _("`%s' has become inaccessible"),
743 /* say nothing... it's still not tailable */
746 else if (prev_errnum
!= errno
)
748 error (0, errno
, "%s", pretty_name (f
));
759 close_fd (fd
, pretty_name (f
));
760 close_fd (f
->fd
, pretty_name (f
));
763 else if (prev_errnum
&& prev_errnum
!= ENOENT
)
766 assert (f
->fd
== -1);
767 error (0, 0, _("`%s' has become accessible"), pretty_name (f
));
769 else if (f
->ino
!= new_stats
.st_ino
|| f
->dev
!= new_stats
.st_dev
)
775 _("`%s' has appeared; following end of new file"),
780 /* Close the old one. */
781 close_fd (f
->fd
, pretty_name (f
));
783 /* File has been replaced (e.g., via log rotation) --
786 _("`%s' has been replaced; following end of new file"),
794 /* This happens when one iteration finds the file missing,
795 then the preceding <dev,inode> pair is reused as the
796 file is recreated. */
801 close_fd (fd
, pretty_name (f
));
807 /* Record new file info in f. */
809 f
->size
= 0; /* Start at the beginning of the file... */
810 f
->dev
= new_stats
.st_dev
;
811 f
->ino
= new_stats
.st_ino
;
812 f
->n_unchanged_stats
= 0;
813 f
->n_consecutive_size_changes
= 0;
814 /* FIXME: check lseek return value */
815 lseek (f
->fd
, f
->size
, SEEK_SET
);
819 /* FIXME: describe */
822 n_live_files (const struct File_spec
*f
, int n_files
)
825 unsigned int n_live
= 0;
827 for (i
= 0; i
< n_files
; i
++)
835 /* Tail NFILES files forever, or until killed.
836 The pertinent information for each file is stored in an entry of F.
837 Loop over each of them, doing an fstat to see if they have changed size,
838 and an occasional open/fstat to see if any dev/ino pair has changed.
839 If none of them have changed size in one iteration, sleep for a
840 while and try again. Continue until the user interrupts us. */
843 tail_forever (struct File_spec
*f
, int nfiles
)
846 int writer_is_dead
= 0;
856 for (i
= 0; i
< nfiles
; i
++)
866 if (fstat (f
[i
].fd
, &stats
) < 0)
870 error (0, errno
, "%s", pretty_name (&f
[i
]));
874 if (stats
.st_size
== f
[i
].size
)
876 f
[i
].n_consecutive_size_changes
= 0;
877 if (++f
[i
].n_unchanged_stats
> max_n_unchanged_stats_between_opens
878 && follow_mode
== Follow_name
)
881 f
[i
].n_unchanged_stats
= 0;
887 ++f
[i
].n_consecutive_size_changes
;
889 /* Ensure that a file that's unlinked or moved aside, yet always
890 growing will be recognized as having been renamed. */
891 if (follow_mode
== Follow_name
892 && (f
[i
].n_consecutive_size_changes
893 > max_n_consecutive_size_changes_between_opens
))
895 f
[i
].n_consecutive_size_changes
= 0;
900 /* This file has changed size. Print out what we can, and
901 then keep looping. */
906 f
[i
].n_unchanged_stats
= 0;
908 if (stats
.st_size
< f
[i
].size
)
910 write_header (pretty_name (&f
[i
]), _("file truncated"));
912 /* FIXME: check lseek return value */
913 lseek (f
[i
].fd
, stats
.st_size
, SEEK_SET
);
914 f
[i
].size
= stats
.st_size
;
921 write_header (pretty_name (&f
[i
]), NULL
);
924 f
[i
].size
+= dump_remainder (pretty_name (&f
[i
]), f
[i
].fd
,
928 if (n_live_files (f
, nfiles
) == 0 && ! reopen_inaccessible_files
)
930 error (0, 0, _("no files remaining"));
934 /* If none of the files changed size, sleep. */
939 sleep (sleep_interval
);
941 /* Once the writer is dead, read the files once more to
942 avoid a race condition. */
943 writer_is_dead
= (pid
!= 0
944 && kill (pid
, 0) != 0
945 /* Handle the case in which you cannot send a
946 signal to the writer, so kill fails and sets
953 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
954 Return 0 if successful, 1 if an error occurred. */
957 tail_bytes (const char *pretty_filename
, int fd
, off_t n_bytes
)
961 /* We need binary input, since `tail' relies on `lseek' and byte counts,
962 while binary output will preserve the style (Unix/DOS) of text file. */
963 SET_BINARY2 (fd
, STDOUT_FILENO
);
965 if (fstat (fd
, &stats
))
967 error (0, errno
, "%s", pretty_filename
);
973 if (S_ISREG (stats
.st_mode
))
975 /* FIXME: check lseek return value */
976 lseek (fd
, n_bytes
, SEEK_CUR
);
978 else if (start_bytes (pretty_filename
, fd
, n_bytes
))
982 dump_remainder (pretty_filename
, fd
, COPY_TO_EOF
);
986 if (S_ISREG (stats
.st_mode
))
988 off_t current_pos
, end_pos
;
989 size_t bytes_remaining
;
991 if ((current_pos
= lseek (fd
, (off_t
) 0, SEEK_CUR
)) != -1
992 && (end_pos
= lseek (fd
, (off_t
) 0, SEEK_END
)) != -1)
995 /* Be careful here. The current position may actually be
996 beyond the end of the file. */
997 bytes_remaining
= (diff
= end_pos
- current_pos
) < 0 ? 0 : diff
;
1001 error (0, errno
, "%s", pretty_filename
);
1005 if (bytes_remaining
<= n_bytes
)
1007 /* From the current position to end of file, there are no
1008 more bytes than have been requested. So reposition the
1009 file pointer to the incoming current position and print
1010 everything after that. */
1011 /* FIXME: check lseek return value */
1012 lseek (fd
, current_pos
, SEEK_SET
);
1016 /* There are more bytes remaining than were requested.
1018 /* FIXME: check lseek return value */
1019 lseek (fd
, -n_bytes
, SEEK_END
);
1021 dump_remainder (pretty_filename
, fd
, n_bytes
);
1024 return pipe_bytes (pretty_filename
, fd
, n_bytes
);
1029 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1030 Return 0 if successful, 1 if an error occurred. */
1033 tail_lines (const char *pretty_filename
, int fd
, long int n_lines
)
1038 /* We need binary input, since `tail' relies on `lseek' and byte counts,
1039 while binary output will preserve the style (Unix/DOS) of text file. */
1040 SET_BINARY2 (fd
, STDOUT_FILENO
);
1042 if (fstat (fd
, &stats
))
1044 error (0, errno
, "%s", pretty_filename
);
1050 if (start_lines (pretty_filename
, fd
, n_lines
))
1052 dump_remainder (pretty_filename
, fd
, COPY_TO_EOF
);
1056 /* Use file_lines only if FD refers to a regular file with
1057 its file pointer positioned at beginning of file. */
1058 /* FIXME: adding the lseek conjunct is a kludge.
1059 Once there's a reasonable test suite, fix the true culprit:
1060 file_lines. file_lines shouldn't presume that the input
1061 file pointer is initially positioned to beginning of file. */
1062 if (S_ISREG (stats
.st_mode
)
1063 && lseek (fd
, (off_t
) 0, SEEK_CUR
) == (off_t
) 0)
1065 length
= lseek (fd
, (off_t
) 0, SEEK_END
);
1066 if (length
!= 0 && file_lines (pretty_filename
, fd
, n_lines
, length
))
1070 return pipe_lines (pretty_filename
, fd
, n_lines
);
1075 /* Display the last N_UNITS units of file FILENAME, open for reading
1077 Return 0 if successful, 1 if an error occurred. */
1080 tail (const char *pretty_filename
, int fd
, off_t n_units
)
1083 return tail_lines (pretty_filename
, fd
, (long) n_units
);
1085 return tail_bytes (pretty_filename
, fd
, n_units
);
1088 /* Display the last N_UNITS units of the file described by F.
1089 Return 0 if successful, 1 if an error occurred. */
1092 tail_file (struct File_spec
*f
, off_t n_units
)
1097 int is_stdin
= (STREQ (f
->name
, "-"));
1101 have_read_stdin
= 1;
1106 fd
= open (f
->name
, O_RDONLY
);
1109 f
->tailable
= !(reopen_inaccessible_files
&& fd
== -1);
1118 error (0, errno
, "%s", pretty_name (f
));
1124 write_header (pretty_name (f
), NULL
);
1125 errors
= tail (pretty_name (f
), fd
, n_units
);
1129 /* FIXME: duplicate code */
1130 if (fstat (fd
, &stats
) < 0)
1134 error (0, errno
, "%s", pretty_name (f
));
1139 close_fd (fd
, pretty_name (f
));
1145 f
->size
= stats
.st_size
;
1146 f
->dev
= stats
.st_dev
;
1147 f
->ino
= stats
.st_ino
;
1148 f
->n_unchanged_stats
= 0;
1149 f
->n_consecutive_size_changes
= 0;
1154 if (!is_stdin
&& close (fd
))
1156 error (0, errno
, "%s", pretty_name (f
));
1165 /* If the command line arguments are of the obsolescent form and the
1166 option string is well-formed, set *FAIL to zero, set *N_UNITS, the
1167 globals COUNT_LINES, FOREVER, and FROM_START, and return non-zero.
1168 Otherwise, if the command line arguments appear to be of the
1169 obsolescent form but the option string is malformed, set *FAIL to
1170 non-zero, don't modify any other parameter or global variable, and
1171 return non-zero. Otherwise, return zero and don't modify any parameter
1172 or global variable. */
1175 parse_obsolescent_option (int argc
, const char *const *argv
,
1176 off_t
*n_units
, int *fail
)
1178 const char *p
= argv
[1];
1179 const char *n_string
= NULL
;
1180 const char *n_string_end
;
1186 /* With the obsolescent form, there is one option string and
1187 (technically) at most one file argument. But we allow two or more
1192 /* If P starts with `+', `-N' (where N is a digit), or `-l',
1193 then it is obsolescent. Return zero otherwise. */
1194 if ( ! (p
[0] == '+' || (p
[0] == '-' && (p
[1] == 'l' || ISDIGIT (p
[1])))) )
1212 while (ISDIGIT (*p
));
1236 /* If (argv[1] begins with a `+' or if it begins with `-' followed
1237 by a digit), but has an invalid suffix character, give a diagnostic
1238 and indicate to caller that this *is* of the obsolescent form,
1239 but that it's an invalid option. */
1240 if (t_from_start
|| n_string
)
1243 _("%c: invalid suffix character in obsolescent option" ), *p
);
1248 /* Otherwise, it might be a valid non-obsolescent option like -n. */
1253 if (n_string
== NULL
)
1254 *n_units
= DEFAULT_N_LINES
;
1258 unsigned long int tmp_ulong
;
1260 s_err
= xstrtoul (n_string
, &end
, 10, &tmp_ulong
, NULL
);
1261 if (s_err
== LONGINT_OK
&& tmp_ulong
<= OFF_T_MAX
)
1262 *n_units
= (off_t
) tmp_ulong
;
1265 /* Extract a NUL-terminated string for the error message. */
1266 size_t len
= n_string_end
- n_string
;
1267 char *n_string_tmp
= xmalloc (len
+ 1);
1269 strncpy (n_string_tmp
, n_string
, len
);
1270 n_string_tmp
[len
] = '\0';
1273 _("%s: %s is so large that it is not representable"),
1274 n_string_tmp
, (count_lines
1275 ? _("number of lines")
1276 : _("number of bytes")));
1277 free (n_string_tmp
);
1286 int posix_pedantic
= (getenv ("POSIXLY_CORRECT") != NULL
);
1288 /* When POSIXLY_CORRECT is set, enforce the `at most one
1289 file argument' requirement. */
1293 too many arguments; When using tail's obsolescent option syntax (%s)\n\
1294 there may be no more than one file argument. Use the equivalent -n or -c\n\
1295 option instead."), argv
[1]);
1300 #if DISABLED /* FIXME: enable or remove this warning. */
1302 Warning: it is not portable to use two or more file arguments with\n\
1303 tail's obsolescent option syntax (%s). Use the equivalent -n or -c\n\
1304 option instead."), argv
[1]);
1309 from_start
= t_from_start
;
1310 count_lines
= t_count_lines
;
1311 forever
= t_forever
;
1318 parse_options (int argc
, char **argv
,
1319 off_t
*n_units
, enum header_mode
*header_mode
)
1324 forever
= from_start
= print_headers
= 0;
1326 while ((c
= getopt_long (argc
, argv
, "c:n:fqs:v", long_options
, NULL
))
1336 count_lines
= (c
== 'n');
1339 else if (*optarg
== '-')
1344 unsigned long int tmp_ulong
;
1345 s_err
= xstrtoul (optarg
, NULL
, 10, &tmp_ulong
, "bkm");
1346 if (s_err
== LONGINT_INVALID
)
1348 error (EXIT_FAILURE
, 0, "%s: %s", optarg
,
1350 ? _("invalid number of lines")
1351 : _("invalid number of bytes")));
1353 if (s_err
!= LONGINT_OK
|| tmp_ulong
> OFF_T_MAX
)
1355 error (EXIT_FAILURE
, 0,
1356 _("%s: %s is so large that it is not representable"),
1358 c
== 'n' ? _("number of lines") : _("number of bytes"));
1360 *n_units
= (off_t
) tmp_ulong
;
1365 case LONG_FOLLOW_OPTION
:
1368 follow_mode
= DEFAULT_FOLLOW_MODE
;
1370 follow_mode
= XARGMATCH ("--follow", optarg
,
1371 follow_mode_string
, follow_mode_map
);
1375 reopen_inaccessible_files
= 1;
1378 case MAX_UNCHANGED_STATS_OPTION
:
1379 /* --max-unchanged-stats=N */
1380 if (xstrtoul (optarg
, NULL
, 10,
1381 &max_n_unchanged_stats_between_opens
, "") != LONGINT_OK
)
1383 error (EXIT_FAILURE
, 0,
1384 _("%s: invalid maximum number of unchanged stats between opens"),
1389 case MAX_CONSECUTIVE_SIZE_CHANGES_OPTION
:
1390 /* --max-consecutive-size-changes=N */
1391 if (xstrtoul (optarg
, NULL
, 10,
1392 &max_n_consecutive_size_changes_between_opens
, "")
1395 error (EXIT_FAILURE
, 0,
1396 _("%s: invalid maximum number of consecutive size changes"),
1404 unsigned long int tmp_ulong
;
1405 s_err
= xstrtoul (optarg
, NULL
, 10, &tmp_ulong
, "");
1406 if (s_err
!= LONGINT_OK
|| tmp_ulong
> PID_T_MAX
)
1408 error (EXIT_FAILURE
, 0, _("%s: invalid PID"), optarg
);
1415 *header_mode
= never
;
1421 unsigned long int tmp_ulong
;
1422 s_err
= xstrtoul (optarg
, NULL
, 10, &tmp_ulong
, "");
1423 if (s_err
!= LONGINT_OK
|| tmp_ulong
> UINT_MAX
)
1425 error (EXIT_FAILURE
, 0,
1426 _("%s: invalid number of seconds"), optarg
);
1428 sleep_interval
= tmp_ulong
;
1433 *header_mode
= always
;
1436 case_GETOPT_HELP_CHAR
;
1438 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1445 if (reopen_inaccessible_files
&& follow_mode
!= Follow_name
)
1446 error (0, 0, _("warning: --retry is useful only when following by name"));
1448 if (pid
&& !forever
)
1450 _("warning: PID ignored; --pid=PID is useful only when following"));
1451 else if (pid
&& kill (pid
, 0) != 0 && errno
== ENOSYS
)
1453 error (0, 0, _("warning: --pid=PID is not supported on this system"));
1459 main (int argc
, char **argv
)
1461 enum header_mode header_mode
= multiple_files
;
1462 int exit_status
= 0;
1463 /* If from_start, the number of items to skip before printing; otherwise,
1464 the number of items at the end of the file to print. Although the type
1465 is signed, the value is never negative. */
1466 off_t n_units
= DEFAULT_N_LINES
;
1469 struct File_spec
*F
;
1472 program_name
= argv
[0];
1473 setlocale (LC_ALL
, "");
1474 bindtextdomain (PACKAGE
, LOCALEDIR
);
1475 textdomain (PACKAGE
);
1477 have_read_stdin
= 0;
1480 int found_obsolescent
;
1482 found_obsolescent
= parse_obsolescent_option (argc
,
1483 (const char *const *) argv
,
1485 if (found_obsolescent
)
1488 exit (EXIT_FAILURE
);
1493 parse_options (argc
, argv
, &n_units
, &header_mode
);
1497 /* To start printing with item N_UNITS from the start of the file, skip
1498 N_UNITS - 1 items. `tail +0' is actually meaningless, but for Unix
1499 compatibility it's treated the same as `tail +1'. */
1506 n_files
= argc
- optind
;
1507 file
= argv
+ optind
;
1511 static char *dummy_stdin
= "-";
1513 file
= &dummy_stdin
;
1516 F
= (struct File_spec
*) xmalloc (n_files
* sizeof (F
[0]));
1517 for (i
= 0; i
< n_files
; i
++)
1518 F
[i
].name
= file
[i
];
1520 if (header_mode
== always
1521 || (header_mode
== multiple_files
&& n_files
> 1))
1524 for (i
= 0; i
< n_files
; i
++)
1525 exit_status
|= tail_file (&F
[i
], n_units
);
1529 SETVBUF (stdout
, NULL
, _IONBF
, 0);
1530 tail_forever (F
, n_files
);
1533 if (have_read_stdin
&& close (0) < 0)
1534 error (EXIT_FAILURE
, errno
, "-");
1535 if (fclose (stdout
) == EOF
)
1536 error (EXIT_FAILURE
, errno
, _("write error"));
1537 exit (exit_status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);