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)
54 /* Number of items to tail. */
55 #define DEFAULT_N_LINES 10
57 /* Size of atomic reads. */
59 # define BUFSIZ (512 * 8)
62 /* A special value for dump_remainder's N_BYTES parameter. */
63 #define COPY_TO_EOF OFF_T_MAX
65 /* FIXME: make Follow_name the default? */
66 #define DEFAULT_FOLLOW_MODE Follow_descriptor
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. */
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,
81 static char const *const follow_mode_string
[] =
83 "descriptor", "name", 0
86 static enum Follow_mode
const follow_mode_map
[] =
88 Follow_descriptor
, Follow_name
,
93 /* The actual file name, or "-" for stdin. */
96 /* File descriptor on which the file is open; -1 if it's not open. */
99 /* The size of the file the last time we checked. */
102 /* The device and inode of the file the last time we checked. */
106 /* See description of DEFAULT_MAX_N_... below. */
107 unsigned int n_unchanged_stats
;
109 /* See description of DEFAULT_MAX_N_... below. */
110 unsigned int n_consecutive_size_changes
;
112 /* A file is tailable if it is a regular file or a fifo and it is
116 /* The value of errno seen last time we checked this file. */
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
;
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
;
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
;
133 /* If nonzero, read from the ends of all specified files until killed. */
136 /* If nonzero, count from start of file instead of end. */
137 static int from_start
;
139 /* If nonzero, print filename headers. */
140 static int print_headers
;
142 /* When to print the filename banners. */
145 multiple_files
, always
, never
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
;
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
;
167 /* The name this program was run with. */
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;
176 /* The process ID of the process (presumably on the current host)
177 that is writing to all followed files. */
180 /* Nonzero if we have ever read standard input. */
181 static int have_read_stdin
;
183 static struct option
const long_options
[] =
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
},
208 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
213 Usage: %s [OPTION]... [FILE]...\n\
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\
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\
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\
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\
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\
257 DEFAULT_N_LINES
, DEFAULT_N_LINES
,
258 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
,
259 DEFAULT_MAX_N_CONSECUTIVE_SIZE_CHANGES
261 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
263 exit (status
== 0 ? EXIT_SUCCESS
: EXIT_FAILURE
);
267 valid_file_spec (struct File_spec
const *f
)
269 /* Exactly one of the following subexpressions must be true. */
270 return ((f
->fd
== -1) ^ (f
->errnum
== 0));
274 pretty_name (struct File_spec
const *f
)
276 return (STREQ (f
->name
, "-") ? "standard input" : f
->name
);
280 xwrite (int fd
, char *const buffer
, size_t n_bytes
)
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"));
289 close_fd (int fd
, const char *filename
)
291 if (fd
!= -1 && fd
!= STDIN_FILENO
&& close (fd
))
293 error (0, errno
, _("closing %s (fd=%d)"), filename
, fd
);
298 write_header (const char *pretty_filename
, const char *comment
)
300 static int first_file
= 1;
302 printf ("%s==> %s%s%s <==\n", (first_file
? "" : "\n"), pretty_filename
,
303 (comment
? ": " : ""),
304 (comment
? comment
: ""));
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. */
313 dump_remainder (const char *pretty_filename
, int fd
, off_t n_bytes
)
318 off_t n_remaining
= n_bytes
;
323 long n
= MIN (n_remaining
, (off_t
) BUFSIZ
);
324 bytes_read
= safe_read (fd
, buffer
, n
);
327 xwrite (STDOUT_FILENO
, buffer
, bytes_read
);
328 n_remaining
-= bytes_read
;
329 n_written
+= bytes_read
;
331 if (bytes_read
== -1)
332 error (EXIT_FAILURE
, errno
, "%s", pretty_filename
);
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. */
346 file_lines (const char *pretty_filename
, int fd
, long int n_lines
,
351 int i
; /* Index into `buffer' for scanning. */
352 off_t pos
= file_length
;
357 /* Set `bytes_read' to the size of the last, probably partial, buffer;
358 0 < `bytes_read' <= `BUFSIZ'. */
359 bytes_read
= pos
% 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. */
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)
370 error (0, errno
, "%s", pretty_filename
);
374 /* Count the incomplete line on files that don't end with a newline. */
375 if (bytes_read
&& buffer
[bytes_read
- 1] != '\n')
380 /* Scan backward, counting the newlines in this bufferfull. */
381 for (i
= bytes_read
- 1; i
>= 0; i
--)
383 /* Have we counted the requested number of newlines yet? */
384 if (buffer
[i
] == '\n' && n_lines
-- == 0)
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
));
395 /* Not enough newlines in that bufferfull. */
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
);
405 /* FIXME: check lseek return value */
406 lseek (fd
, pos
, SEEK_SET
);
408 while ((bytes_read
= safe_read (fd
, buffer
, BUFSIZ
)) > 0);
410 if (bytes_read
== -1)
412 error (0, errno
, "%s", pretty_filename
);
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. */
425 pipe_lines (const char *pretty_filename
, int fd
, long int n_lines
)
431 struct linebuffer
*next
;
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. */
439 first
= last
= (LBUFFER
*) xmalloc (sizeof (LBUFFER
));
440 first
->nbytes
= first
->nlines
= 0;
442 tmp
= (LBUFFER
*) xmalloc (sizeof (LBUFFER
));
444 /* Input is always read into a fresh buffer. */
445 while ((tmp
->nbytes
= safe_read (fd
, tmp
->buffer
, BUFSIZ
)) > 0)
450 /* Count the number of newlines just read. */
451 for (i
= 0; i
< tmp
->nbytes
; i
++)
452 if (tmp
->buffer
[i
] == '\n')
454 total_lines
+= tmp
->nlines
;
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
)
461 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
462 last
->nbytes
+= tmp
->nbytes
;
463 last
->nlines
+= tmp
->nlines
;
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
472 last
= last
->next
= tmp
;
473 if (total_lines
- first
->nlines
> n_lines
)
476 total_lines
-= first
->nlines
;
480 tmp
= (LBUFFER
*) xmalloc (sizeof (LBUFFER
));
483 if (tmp
->nbytes
== -1)
485 error (0, errno
, "%s", pretty_filename
);
493 /* This prevents a core dump when the pipe contains no newlines. */
497 /* Count the incomplete line on files that don't end with a newline. */
498 if (last
->buffer
[last
->nbytes
- 1] != '\n')
504 /* Run through the list, printing lines. First, skip over unneeded
506 for (tmp
= first
; total_lines
- tmp
->nlines
> n_lines
; tmp
= tmp
->next
)
507 total_lines
-= tmp
->nlines
;
509 /* Find the correct beginning, then print the rest of the file. */
510 if (total_lines
> n_lines
)
514 /* Skip `total_lines' - `n_lines' newlines. We made sure that
515 `total_lines' - `n_lines' <= `tmp->nlines'. */
517 for (i
= total_lines
- n_lines
; i
; --i
)
518 while (*cp
++ != '\n')
520 i
= cp
- tmp
->buffer
;
524 xwrite (STDOUT_FILENO
, &tmp
->buffer
[i
], tmp
->nbytes
- i
);
526 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
527 xwrite (STDOUT_FILENO
, tmp
->buffer
, tmp
->nbytes
);
533 free ((char *) first
);
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. */
544 pipe_bytes (const char *pretty_filename
, int fd
, off_t n_bytes
)
550 struct charbuffer
*next
;
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. */
558 first
= last
= (CBUFFER
*) xmalloc (sizeof (CBUFFER
));
561 tmp
= (CBUFFER
*) xmalloc (sizeof (CBUFFER
));
563 /* Input is always read into a fresh buffer. */
564 while ((tmp
->nbytes
= safe_read (fd
, tmp
->buffer
, BUFSIZ
)) > 0)
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
)
574 memcpy (&last
->buffer
[last
->nbytes
], tmp
->buffer
, tmp
->nbytes
);
575 last
->nbytes
+= tmp
->nbytes
;
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
584 last
= last
->next
= tmp
;
585 if (total_bytes
- first
->nbytes
> n_bytes
)
588 total_bytes
-= first
->nbytes
;
593 tmp
= (CBUFFER
*) xmalloc (sizeof (CBUFFER
));
597 if (tmp
->nbytes
== -1)
599 error (0, errno
, "%s", pretty_filename
);
607 /* Run through the list, printing characters. First, skip over unneeded
609 for (tmp
= first
; total_bytes
- tmp
->nbytes
> n_bytes
; tmp
= tmp
->next
)
610 total_bytes
-= tmp
->nbytes
;
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
;
618 xwrite (STDOUT_FILENO
, &tmp
->buffer
[i
], tmp
->nbytes
- i
);
620 for (tmp
= tmp
->next
; tmp
; tmp
= tmp
->next
)
621 xwrite (STDOUT_FILENO
, tmp
->buffer
, tmp
->nbytes
);
627 free ((char *) first
);
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. */
638 start_bytes (const char *pretty_filename
, int fd
, off_t n_bytes
)
643 while (n_bytes
> 0 && (bytes_read
= safe_read (fd
, buffer
, BUFSIZ
)) > 0)
644 n_bytes
-= bytes_read
;
645 if (bytes_read
== -1)
647 error (0, errno
, "%s", pretty_filename
);
650 else if (n_bytes
< 0)
651 xwrite (STDOUT_FILENO
, &buffer
[bytes_read
+ n_bytes
], -n_bytes
);
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. */
660 start_lines (const char *pretty_filename
, int fd
, long int n_lines
)
664 int bytes_to_skip
= 0;
666 while (n_lines
&& (bytes_read
= safe_read (fd
, buffer
, BUFSIZ
)) > 0)
669 while (bytes_to_skip
< bytes_read
)
670 if (buffer
[bytes_to_skip
++] == '\n' && --n_lines
== 0)
673 if (bytes_read
== -1)
675 error (0, errno
, "%s", pretty_filename
);
678 else if (bytes_to_skip
< bytes_read
)
680 xwrite (STDOUT_FILENO
, &buffer
[bytes_to_skip
],
681 bytes_read
- bytes_to_skip
);
686 /* FIXME: describe */
689 recheck (struct File_spec
*f
)
691 /* open/fstat the file and announce if dev/ino have changed */
692 struct stat new_stats
;
695 int is_stdin
= (STREQ (f
->name
, "-"));
696 int was_tailable
= f
->tailable
;
697 int prev_errnum
= f
->errnum
;
700 assert (valid_file_spec (f
));
702 fd
= (is_stdin
? STDIN_FILENO
: open (f
->name
, O_RDONLY
));
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);
708 if (fd
== -1 || fstat (fd
, &new_stats
) < 0)
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"),
725 /* say nothing... it's still not tailable */
728 else if (prev_errnum
!= errno
)
730 error (0, errno
, "%s", pretty_name (f
));
733 else if (!S_ISREG (new_stats
.st_mode
)
734 && !S_ISFIFO (new_stats
.st_mode
))
739 _("`%s' has been replaced with a non-regular file; \
740 cannot follow end of non-regular file"),
751 close_fd (fd
, pretty_name (f
));
752 close_fd (f
->fd
, pretty_name (f
));
755 else if (prev_errnum
&& prev_errnum
!= ENOENT
)
758 assert (f
->fd
== -1);
759 error (0, 0, _("`%s' has become accessible"), pretty_name (f
));
761 else if (f
->ino
!= new_stats
.st_ino
|| f
->dev
!= new_stats
.st_dev
)
767 _("`%s' has appeared; following end of new file"),
772 /* Close the old one. */
773 close_fd (f
->fd
, pretty_name (f
));
775 /* File has been replaced (e.g., via log rotation) --
778 _("`%s' has been replaced; following end of new file"),
784 close_fd (fd
, pretty_name (f
));
789 /* Record new file info in f. */
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
);
801 /* FIXME: describe */
804 n_live_files (const struct File_spec
*f
, int n_files
)
807 unsigned int n_live
= 0;
809 for (i
= 0; i
< n_files
; i
++)
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. */
825 tail_forever (struct File_spec
*f
, int nfiles
)
828 int writer_is_dead
= 0;
838 for (i
= 0; i
< nfiles
; i
++)
848 if (fstat (f
[i
].fd
, &stats
) < 0)
850 error (0, errno
, "%s", pretty_name (&f
[i
]));
856 if (stats
.st_size
== f
[i
].size
)
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
)
863 f
[i
].n_unchanged_stats
= 0;
869 ++f
[i
].n_consecutive_size_changes
;
871 /* Ensure that a file that's unlinked or moved aside, yet always
872 growing will be recognized as having been renamed. */
873 if (follow_mode
== Follow_name
874 && (f
[i
].n_consecutive_size_changes
875 > max_n_consecutive_size_changes_between_opens
))
877 f
[i
].n_consecutive_size_changes
= 0;
882 /* This file has changed size. Print out what we can, and
883 then keep looping. */
888 f
[i
].n_unchanged_stats
= 0;
890 if (stats
.st_size
< f
[i
].size
)
892 write_header (pretty_name (&f
[i
]), _("file truncated"));
894 /* FIXME: check lseek return value */
895 lseek (f
[i
].fd
, stats
.st_size
, SEEK_SET
);
896 f
[i
].size
= stats
.st_size
;
903 write_header (pretty_name (&f
[i
]), NULL
);
906 f
[i
].size
+= dump_remainder (pretty_name (&f
[i
]), f
[i
].fd
,
910 if (n_live_files (f
, nfiles
) == 0 && ! reopen_inaccessible_files
)
912 error (0, 0, _("no files remaining"));
916 /* If none of the files changed size, sleep. */
921 sleep (sleep_interval
);
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
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. */
939 tail_bytes (const char *pretty_filename
, int fd
, off_t n_bytes
)
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
);
947 if (fstat (fd
, &stats
))
949 error (0, errno
, "%s", pretty_filename
);
955 if (S_ISREG (stats
.st_mode
))
957 /* FIXME: check lseek return value */
958 lseek (fd
, n_bytes
, SEEK_CUR
);
960 else if (start_bytes (pretty_filename
, fd
, n_bytes
))
964 dump_remainder (pretty_filename
, fd
, COPY_TO_EOF
);
968 if (S_ISREG (stats
.st_mode
))
970 off_t current_pos
, end_pos
;
971 size_t bytes_remaining
;
973 if ((current_pos
= lseek (fd
, (off_t
) 0, SEEK_CUR
)) != -1
974 && (end_pos
= lseek (fd
, (off_t
) 0, SEEK_END
)) != -1)
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
;
983 error (0, errno
, "%s", pretty_filename
);
987 if (bytes_remaining
<= n_bytes
)
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
);
998 /* There are more bytes remaining than were requested.
1000 /* FIXME: check lseek return value */
1001 lseek (fd
, -n_bytes
, SEEK_END
);
1003 dump_remainder (pretty_filename
, fd
, n_bytes
);
1006 return pipe_bytes (pretty_filename
, fd
, n_bytes
);
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. */
1015 tail_lines (const char *pretty_filename
, int fd
, long int n_lines
)
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
);
1024 if (fstat (fd
, &stats
))
1026 error (0, errno
, "%s", pretty_filename
);
1032 if (start_lines (pretty_filename
, fd
, n_lines
))
1034 dump_remainder (pretty_filename
, fd
, COPY_TO_EOF
);
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)
1047 length
= lseek (fd
, (off_t
) 0, SEEK_END
);
1048 if (length
!= 0 && file_lines (pretty_filename
, fd
, n_lines
, length
))
1052 return pipe_lines (pretty_filename
, fd
, n_lines
);
1057 /* Display the last N_UNITS units of file FILENAME, open for reading
1059 Return 0 if successful, 1 if an error occurred. */
1062 tail (const char *pretty_filename
, int fd
, off_t n_units
)
1065 return tail_lines (pretty_filename
, fd
, (long) n_units
);
1067 return tail_bytes (pretty_filename
, fd
, n_units
);
1070 /* Display the last N_UNITS units of the file described by F.
1071 Return 0 if successful, 1 if an error occurred. */
1074 tail_file (struct File_spec
*f
, off_t n_units
)
1079 int is_stdin
= (STREQ (f
->name
, "-"));
1083 have_read_stdin
= 1;
1088 fd
= open (f
->name
, O_RDONLY
);
1091 f
->tailable
= !(reopen_inaccessible_files
&& fd
== -1);
1100 error (0, errno
, "%s", pretty_name (f
));
1106 write_header (pretty_name (f
), NULL
);
1107 errors
= tail (pretty_name (f
), fd
, n_units
);
1111 /* FIXME: duplicate code */
1112 if (fstat (fd
, &stats
) < 0)
1114 error (0, errno
, "%s", pretty_name (f
));
1118 else if (!S_ISREG (stats
.st_mode
) && !S_ISFIFO (stats
.st_mode
))
1120 error (0, 0, _("%s: cannot follow end of non-regular file"),
1127 close_fd (fd
, pretty_name (f
));
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;
1142 if (!is_stdin
&& close (fd
))
1144 error (0, errno
, "%s", pretty_name (f
));
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. */
1163 parse_obsolescent_option (int argc
, const char *const *argv
,
1164 off_t
*n_units
, int *fail
)
1166 const char *p
= argv
[1];
1167 const char *n_string
= NULL
;
1168 const char *n_string_end
;
1174 /* With the obsolescent form, there is one option string and
1175 (technically) at most one file argument. But we allow two or more
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])))) )
1200 while (ISDIGIT (*p
));
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
)
1231 _("%c: invalid suffix character in obsolescent option" ), *p
);
1236 /* Otherwise, it might be a valid non-obsolescent option like -n. */
1241 if (n_string
== NULL
)
1242 *n_units
= DEFAULT_N_LINES
;
1246 unsigned long int tmp_ulong
;
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
;
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);
1257 strncpy (n_string_tmp
, n_string
, len
);
1258 n_string_tmp
[len
] = '\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
);
1274 int posix_pedantic
= (getenv ("POSIXLY_CORRECT") != NULL
);
1276 /* When POSIXLY_CORRECT is set, enforce the `at most one
1277 file argument' requirement. */
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]);
1288 #if DISABLED /* FIXME: enable or remove this warning. */
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]);
1297 from_start
= t_from_start
;
1298 count_lines
= t_count_lines
;
1299 forever
= t_forever
;
1306 parse_options (int argc
, char **argv
,
1307 off_t
*n_units
, enum header_mode
*header_mode
)
1312 forever
= from_start
= print_headers
= 0;
1314 while ((c
= getopt_long (argc
, argv
, "c:n:f::qs:v", long_options
, NULL
))
1324 count_lines
= (c
== 'n');
1327 else if (*optarg
== '-')
1332 unsigned long int tmp_ulong
;
1333 s_err
= xstrtoul (optarg
, NULL
, 10, &tmp_ulong
, "bkm");
1334 if (s_err
== LONGINT_INVALID
)
1336 error (EXIT_FAILURE
, 0, "%s: %s", optarg
,
1338 ? _("invalid number of lines")
1339 : _("invalid number of bytes")));
1341 if (s_err
!= LONGINT_OK
|| tmp_ulong
> OFF_T_MAX
)
1343 error (EXIT_FAILURE
, 0,
1344 _("%s: %s is so large that it is not representable"),
1346 c
== 'n' ? _("number of lines") : _("number of bytes"));
1348 *n_units
= (off_t
) tmp_ulong
;
1355 follow_mode
= DEFAULT_FOLLOW_MODE
;
1357 follow_mode
= XARGMATCH ("--follow", optarg
,
1358 follow_mode_string
, follow_mode_map
);
1362 reopen_inaccessible_files
= 1;
1366 /* --max-unchanged-stats=N */
1367 if (xstrtoul (optarg
, NULL
, 10,
1368 &max_n_unchanged_stats_between_opens
, "") != LONGINT_OK
)
1370 error (EXIT_FAILURE
, 0,
1371 _("%s: invalid maximum number of unchanged stats between opens"),
1377 /* --max-consecutive-size-changes=N */
1378 if (xstrtoul (optarg
, NULL
, 10,
1379 &max_n_consecutive_size_changes_between_opens
, "")
1382 error (EXIT_FAILURE
, 0,
1383 _("%s: invalid maximum number of consecutive size changes"),
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
)
1395 error (EXIT_FAILURE
, 0, _("%s: invalid PID"), optarg
);
1402 *header_mode
= never
;
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
)
1412 error (EXIT_FAILURE
, 0,
1413 _("%s: invalid number of seconds"), optarg
);
1415 sleep_interval
= tmp_ulong
;
1420 *header_mode
= always
;
1423 case_GETOPT_HELP_CHAR
;
1425 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1432 if (reopen_inaccessible_files
&& follow_mode
!= Follow_name
)
1433 error (0, 0, _("warning: --retry is useful only when following by name"));
1435 if (pid
&& !forever
)
1437 _("warning: PID ignored; --pid=PID is useful only when following"));
1441 main (int argc
, char **argv
)
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
;
1451 struct File_spec
*F
;
1454 program_name
= argv
[0];
1455 setlocale (LC_ALL
, "");
1456 bindtextdomain (PACKAGE
, LOCALEDIR
);
1457 textdomain (PACKAGE
);
1459 have_read_stdin
= 0;
1462 int found_obsolescent
;
1464 found_obsolescent
= parse_obsolescent_option (argc
,
1465 (const char *const *) argv
,
1467 if (found_obsolescent
)
1470 exit (EXIT_FAILURE
);
1475 parse_options (argc
, argv
, &n_units
, &header_mode
);
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'. */
1488 n_files
= argc
- optind
;
1489 file
= argv
+ optind
;
1493 static char *dummy_stdin
= "-";
1495 file
= &dummy_stdin
;
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
];
1502 if (header_mode
== always
1503 || (header_mode
== multiple_files
&& n_files
> 1))
1506 for (i
= 0; i
< n_files
; i
++)
1507 exit_status
|= tail_file (&F
[i
], n_units
);
1511 SETVBUF (stdout
, NULL
, _IONBF
, 0);
1512 tail_forever (F
, n_files
);
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
);