tests: adjust memory limits in head-c.sh
[coreutils.git] / src / tail.c
blob781adf200df150b295e8a559373fb2698aaa5e44
1 /* tail -- output the last part of file(s)
2 Copyright (C) 1989-2016 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 3 of the License, or
7 (at your option) any later version.
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, see <http://www.gnu.org/licenses/>. */
17 /* Can display any amount of data, unlike the Unix version, which uses
18 a fixed size buffer and therefore can only deliver a limited number
19 of lines.
21 Original version by Paul Rubin <phr@ocf.berkeley.edu>.
22 Extensions by David MacKenzie <djm@gnu.ai.mit.edu>.
23 tail -f for multiple files by Ian Lance Taylor <ian@airs.com>.
24 inotify back-end by Giuseppe Scrivano <gscrivano@gnu.org>. */
26 #include <config.h>
28 #include <stdio.h>
29 #include <assert.h>
30 #include <getopt.h>
31 #include <sys/types.h>
32 #include <signal.h>
34 #include "system.h"
35 #include "argmatch.h"
36 #include "c-strtod.h"
37 #include "error.h"
38 #include "fcntl--.h"
39 #include "isapipe.h"
40 #include "posixver.h"
41 #include "quote.h"
42 #include "safe-read.h"
43 #include "stat-size.h"
44 #include "stat-time.h"
45 #include "xfreopen.h"
46 #include "xnanosleep.h"
47 #include "xdectoint.h"
48 #include "xstrtol.h"
49 #include "xstrtod.h"
51 #if HAVE_INOTIFY
52 # include "hash.h"
53 # include <sys/inotify.h>
54 /* 'select' is used by tail_forever_inotify. */
55 # include <sys/select.h>
57 /* inotify needs to know if a file is local. */
58 # include "fs.h"
59 # include "fs-is-local.h"
60 # if HAVE_SYS_STATFS_H
61 # include <sys/statfs.h>
62 # elif HAVE_SYS_VFS_H
63 # include <sys/vfs.h>
64 # endif
65 #endif
67 /* The official name of this program (e.g., no 'g' prefix). */
68 #define PROGRAM_NAME "tail"
70 #define AUTHORS \
71 proper_name ("Paul Rubin"), \
72 proper_name ("David MacKenzie"), \
73 proper_name ("Ian Lance Taylor"), \
74 proper_name ("Jim Meyering")
76 /* Number of items to tail. */
77 #define DEFAULT_N_LINES 10
79 /* Special values for dump_remainder's N_BYTES parameter. */
80 #define COPY_TO_EOF UINTMAX_MAX
81 #define COPY_A_BUFFER (UINTMAX_MAX - 1)
83 /* FIXME: make Follow_name the default? */
84 #define DEFAULT_FOLLOW_MODE Follow_descriptor
86 enum Follow_mode
88 /* Follow the name of each file: if the file is renamed, try to reopen
89 that name and track the end of the new file if/when it's recreated.
90 This is useful for tracking logs that are occasionally rotated. */
91 Follow_name = 1,
93 /* Follow each descriptor obtained upon opening a file.
94 That means we'll continue to follow the end of a file even after
95 it has been renamed or unlinked. */
96 Follow_descriptor = 2
99 /* The types of files for which tail works. */
100 #define IS_TAILABLE_FILE_TYPE(Mode) \
101 (S_ISREG (Mode) || S_ISFIFO (Mode) || S_ISSOCK (Mode) || S_ISCHR (Mode))
103 static char const *const follow_mode_string[] =
105 "descriptor", "name", NULL
108 static enum Follow_mode const follow_mode_map[] =
110 Follow_descriptor, Follow_name,
113 struct File_spec
115 /* The actual file name, or "-" for stdin. */
116 char *name;
118 /* Attributes of the file the last time we checked. */
119 off_t size;
120 struct timespec mtime;
121 dev_t dev;
122 ino_t ino;
123 mode_t mode;
125 /* The specified name initially referred to a directory or some other
126 type for which tail isn't meaningful. Unlike for a permission problem
127 (tailable, below) once this is set, the name is not checked ever again. */
128 bool ignore;
130 /* See the description of fremote. */
131 bool remote;
133 /* A file is tailable if it exists, is readable, and is of type
134 IS_TAILABLE_FILE_TYPE. */
135 bool tailable;
137 /* File descriptor on which the file is open; -1 if it's not open. */
138 int fd;
140 /* The value of errno seen last time we checked this file. */
141 int errnum;
143 /* 1 if O_NONBLOCK is clear, 0 if set, -1 if not known. */
144 int blocking;
146 #if HAVE_INOTIFY
147 /* The watch descriptor used by inotify. */
148 int wd;
150 /* The parent directory watch descriptor. It is used only
151 * when Follow_name is used. */
152 int parent_wd;
154 /* Offset in NAME of the basename part. */
155 size_t basename_start;
156 #endif
158 /* See description of DEFAULT_MAX_N_... below. */
159 uintmax_t n_unchanged_stats;
162 /* Keep trying to open a file even if it is inaccessible when tail starts
163 or if it becomes inaccessible later -- useful only with -f. */
164 static bool reopen_inaccessible_files;
166 /* If true, interpret the numeric argument as the number of lines.
167 Otherwise, interpret it as the number of bytes. */
168 static bool count_lines;
170 /* Whether we follow the name of each file or the file descriptor
171 that is initially associated with each name. */
172 static enum Follow_mode follow_mode = Follow_descriptor;
174 /* If true, read from the ends of all specified files until killed. */
175 static bool forever;
177 /* If true, count from start of file instead of end. */
178 static bool from_start;
180 /* If true, print filename headers. */
181 static bool print_headers;
183 /* Character to split lines by. */
184 static char line_end;
186 /* When to print the filename banners. */
187 enum header_mode
189 multiple_files, always, never
192 /* When tailing a file by name, if there have been this many consecutive
193 iterations for which the file has not changed, then open/fstat
194 the file to determine if that file name is still associated with the
195 same device/inode-number pair as before. This option is meaningful only
196 when following by name. --max-unchanged-stats=N */
197 #define DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS 5
198 static uintmax_t max_n_unchanged_stats_between_opens =
199 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS;
201 /* The process ID of the process (presumably on the current host)
202 that is writing to all followed files. */
203 static pid_t pid;
205 /* True if we have ever read standard input. */
206 static bool have_read_stdin;
208 /* If nonzero, skip the is-regular-file test used to determine whether
209 to use the lseek optimization. Instead, use the more general (and
210 more expensive) code unconditionally. Intended solely for testing. */
211 static bool presume_input_pipe;
213 /* If nonzero then don't use inotify even if available. */
214 static bool disable_inotify;
216 /* For long options that have no equivalent short option, use a
217 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
218 enum
220 RETRY_OPTION = CHAR_MAX + 1,
221 MAX_UNCHANGED_STATS_OPTION,
222 PID_OPTION,
223 PRESUME_INPUT_PIPE_OPTION,
224 LONG_FOLLOW_OPTION,
225 DISABLE_INOTIFY_OPTION
228 static struct option const long_options[] =
230 {"bytes", required_argument, NULL, 'c'},
231 {"follow", optional_argument, NULL, LONG_FOLLOW_OPTION},
232 {"lines", required_argument, NULL, 'n'},
233 {"max-unchanged-stats", required_argument, NULL, MAX_UNCHANGED_STATS_OPTION},
234 {"-disable-inotify", no_argument, NULL,
235 DISABLE_INOTIFY_OPTION}, /* do not document */
236 {"pid", required_argument, NULL, PID_OPTION},
237 {"-presume-input-pipe", no_argument, NULL,
238 PRESUME_INPUT_PIPE_OPTION}, /* do not document */
239 {"quiet", no_argument, NULL, 'q'},
240 {"retry", no_argument, NULL, RETRY_OPTION},
241 {"silent", no_argument, NULL, 'q'},
242 {"sleep-interval", required_argument, NULL, 's'},
243 {"verbose", no_argument, NULL, 'v'},
244 {"zero-terminated", no_argument, NULL, 'z'},
245 {GETOPT_HELP_OPTION_DECL},
246 {GETOPT_VERSION_OPTION_DECL},
247 {NULL, 0, NULL, 0}
250 void
251 usage (int status)
253 if (status != EXIT_SUCCESS)
254 emit_try_help ();
255 else
257 printf (_("\
258 Usage: %s [OPTION]... [FILE]...\n\
260 program_name);
261 printf (_("\
262 Print the last %d lines of each FILE to standard output.\n\
263 With more than one FILE, precede each with a header giving the file name.\n\
264 "), DEFAULT_N_LINES);
266 emit_stdin_note ();
267 emit_mandatory_arg_note ();
269 fputs (_("\
270 -c, --bytes=[+]NUM output the last NUM bytes; or use -c +NUM to\n\
271 output starting with byte NUM of each file\n\
272 "), stdout);
273 fputs (_("\
274 -f, --follow[={name|descriptor}]\n\
275 output appended data as the file grows;\n\
276 an absent option argument means 'descriptor'\n\
277 -F same as --follow=name --retry\n\
278 "), stdout);
279 printf (_("\
280 -n, --lines=[+]NUM output the last NUM lines, instead of the last %d;\n\
281 or use -n +NUM to output starting with line NUM\n\
282 --max-unchanged-stats=N\n\
283 with --follow=name, reopen a FILE which has not\n\
284 changed size after N (default %d) iterations\n\
285 to see if it has been unlinked or renamed\n\
286 (this is the usual case of rotated log files);\n\
287 with inotify, this option is rarely useful\n\
289 DEFAULT_N_LINES,
290 DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS
292 fputs (_("\
293 --pid=PID with -f, terminate after process ID, PID dies\n\
294 -q, --quiet, --silent never output headers giving file names\n\
295 --retry keep trying to open a file if it is inaccessible\n\
296 "), stdout);
297 fputs (_("\
298 -s, --sleep-interval=N with -f, sleep for approximately N seconds\n\
299 (default 1.0) between iterations;\n\
300 with inotify and --pid=P, check process P at\n\
301 least once every N seconds\n\
302 -v, --verbose always output headers giving file names\n\
303 "), stdout);
304 fputs (_("\
305 -z, --zero-terminated line delimiter is NUL, not newline\n\
306 "), stdout);
307 fputs (HELP_OPTION_DESCRIPTION, stdout);
308 fputs (VERSION_OPTION_DESCRIPTION, stdout);
309 fputs (_("\
311 NUM may have a multiplier suffix:\n\
312 b 512, kB 1000, K 1024, MB 1000*1000, M 1024*1024,\n\
313 GB 1000*1000*1000, G 1024*1024*1024, and so on for T, P, E, Z, Y.\n\
315 "), stdout);
316 fputs (_("\
317 With --follow (-f), tail defaults to following the file descriptor, which\n\
318 means that even if a tail'ed file is renamed, tail will continue to track\n\
319 its end. This default behavior is not desirable when you really want to\n\
320 track the actual name of the file, not the file descriptor (e.g., log\n\
321 rotation). Use --follow=name in that case. That causes tail to track the\n\
322 named file in a way that accommodates renaming, removal and creation.\n\
323 "), stdout);
324 emit_ancillary_info (PROGRAM_NAME);
326 exit (status);
329 static bool
330 valid_file_spec (struct File_spec const *f)
332 /* Exactly one of the following subexpressions must be true. */
333 return ((f->fd == -1) ^ (f->errnum == 0));
336 static char const *
337 pretty_name (struct File_spec const *f)
339 return (STREQ (f->name, "-") ? _("standard input") : f->name);
342 /* Record a file F with descriptor FD, size SIZE, status ST, and
343 blocking status BLOCKING. */
345 static void
346 record_open_fd (struct File_spec *f, int fd,
347 off_t size, struct stat const *st,
348 int blocking)
350 f->fd = fd;
351 f->size = size;
352 f->mtime = get_stat_mtime (st);
353 f->dev = st->st_dev;
354 f->ino = st->st_ino;
355 f->mode = st->st_mode;
356 f->blocking = blocking;
357 f->n_unchanged_stats = 0;
358 f->ignore = false;
361 /* Close the file with descriptor FD and name FILENAME. */
363 static void
364 close_fd (int fd, const char *filename)
366 if (fd != -1 && fd != STDIN_FILENO && close (fd))
368 error (0, errno, _("closing %s (fd=%d)"), quoteaf (filename), fd);
372 static void
373 write_header (const char *pretty_filename)
375 static bool first_file = true;
377 printf ("%s==> %s <==\n", (first_file ? "" : "\n"), pretty_filename);
378 first_file = false;
381 /* Write N_BYTES from BUFFER to stdout.
382 Exit immediately on error with a single diagnostic. */
384 static void
385 xwrite_stdout (char const *buffer, size_t n_bytes)
387 if (n_bytes > 0 && fwrite (buffer, 1, n_bytes, stdout) < n_bytes)
389 clearerr (stdout); /* To avoid redundant close_stdout diagnostic. */
390 error (EXIT_FAILURE, errno, _("error writing %s"),
391 quoteaf ("standard output"));
395 /* Read and output N_BYTES of file PRETTY_FILENAME starting at the current
396 position in FD. If N_BYTES is COPY_TO_EOF, then copy until end of file.
397 If N_BYTES is COPY_A_BUFFER, then copy at most one buffer's worth.
398 Return the number of bytes read from the file. */
400 static uintmax_t
401 dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes)
403 uintmax_t n_written;
404 uintmax_t n_remaining = n_bytes;
406 n_written = 0;
407 while (1)
409 char buffer[BUFSIZ];
410 size_t n = MIN (n_remaining, BUFSIZ);
411 size_t bytes_read = safe_read (fd, buffer, n);
412 if (bytes_read == SAFE_READ_ERROR)
414 if (errno != EAGAIN)
415 error (EXIT_FAILURE, errno, _("error reading %s"),
416 quoteaf (pretty_filename));
417 break;
419 if (bytes_read == 0)
420 break;
421 xwrite_stdout (buffer, bytes_read);
422 n_written += bytes_read;
423 if (n_bytes != COPY_TO_EOF)
425 n_remaining -= bytes_read;
426 if (n_remaining == 0 || n_bytes == COPY_A_BUFFER)
427 break;
431 return n_written;
434 /* Call lseek with the specified arguments, where file descriptor FD
435 corresponds to the file, FILENAME.
436 Give a diagnostic and exit nonzero if lseek fails.
437 Otherwise, return the resulting offset. */
439 static off_t
440 xlseek (int fd, off_t offset, int whence, char const *filename)
442 off_t new_offset = lseek (fd, offset, whence);
443 char buf[INT_BUFSIZE_BOUND (offset)];
444 char *s;
446 if (0 <= new_offset)
447 return new_offset;
449 s = offtostr (offset, buf);
450 switch (whence)
452 case SEEK_SET:
453 error (0, errno, _("%s: cannot seek to offset %s"),
454 quotef (filename), s);
455 break;
456 case SEEK_CUR:
457 error (0, errno, _("%s: cannot seek to relative offset %s"),
458 quotef (filename), s);
459 break;
460 case SEEK_END:
461 error (0, errno, _("%s: cannot seek to end-relative offset %s"),
462 quotef (filename), s);
463 break;
464 default:
465 abort ();
468 exit (EXIT_FAILURE);
471 /* Print the last N_LINES lines from the end of file FD.
472 Go backward through the file, reading 'BUFSIZ' bytes at a time (except
473 probably the first), until we hit the start of the file or have
474 read NUMBER newlines.
475 START_POS is the starting position of the read pointer for the file
476 associated with FD (may be nonzero).
477 END_POS is the file offset of EOF (one larger than offset of last byte).
478 Return true if successful. */
480 static bool
481 file_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
482 off_t start_pos, off_t end_pos, uintmax_t *read_pos)
484 char buffer[BUFSIZ];
485 size_t bytes_read;
486 off_t pos = end_pos;
488 if (n_lines == 0)
489 return true;
491 /* Set 'bytes_read' to the size of the last, probably partial, buffer;
492 0 < 'bytes_read' <= 'BUFSIZ'. */
493 bytes_read = (pos - start_pos) % BUFSIZ;
494 if (bytes_read == 0)
495 bytes_read = BUFSIZ;
496 /* Make 'pos' a multiple of 'BUFSIZ' (0 if the file is short), so that all
497 reads will be on block boundaries, which might increase efficiency. */
498 pos -= bytes_read;
499 xlseek (fd, pos, SEEK_SET, pretty_filename);
500 bytes_read = safe_read (fd, buffer, bytes_read);
501 if (bytes_read == SAFE_READ_ERROR)
503 error (0, errno, _("error reading %s"), quoteaf (pretty_filename));
504 return false;
506 *read_pos = pos + bytes_read;
508 /* Count the incomplete line on files that don't end with a newline. */
509 if (bytes_read && buffer[bytes_read - 1] != line_end)
510 --n_lines;
514 /* Scan backward, counting the newlines in this bufferfull. */
516 size_t n = bytes_read;
517 while (n)
519 char const *nl;
520 nl = memrchr (buffer, line_end, n);
521 if (nl == NULL)
522 break;
523 n = nl - buffer;
524 if (n_lines-- == 0)
526 /* If this newline isn't the last character in the buffer,
527 output the part that is after it. */
528 if (n != bytes_read - 1)
529 xwrite_stdout (nl + 1, bytes_read - (n + 1));
530 *read_pos += dump_remainder (pretty_filename, fd,
531 end_pos - (pos + bytes_read));
532 return true;
536 /* Not enough newlines in that bufferfull. */
537 if (pos == start_pos)
539 /* Not enough lines in the file; print everything from
540 start_pos to the end. */
541 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
542 *read_pos = start_pos + dump_remainder (pretty_filename, fd,
543 end_pos);
544 return true;
546 pos -= BUFSIZ;
547 xlseek (fd, pos, SEEK_SET, pretty_filename);
549 bytes_read = safe_read (fd, buffer, BUFSIZ);
550 if (bytes_read == SAFE_READ_ERROR)
552 error (0, errno, _("error reading %s"), quoteaf (pretty_filename));
553 return false;
556 *read_pos = pos + bytes_read;
558 while (bytes_read > 0);
560 return true;
563 /* Print the last N_LINES lines from the end of the standard input,
564 open for reading as pipe FD.
565 Buffer the text as a linked list of LBUFFERs, adding them as needed.
566 Return true if successful. */
568 static bool
569 pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
570 uintmax_t *read_pos)
572 struct linebuffer
574 char buffer[BUFSIZ];
575 size_t nbytes;
576 size_t nlines;
577 struct linebuffer *next;
579 typedef struct linebuffer LBUFFER;
580 LBUFFER *first, *last, *tmp;
581 size_t total_lines = 0; /* Total number of newlines in all buffers. */
582 bool ok = true;
583 size_t n_read; /* Size in bytes of most recent read */
585 first = last = xmalloc (sizeof (LBUFFER));
586 first->nbytes = first->nlines = 0;
587 first->next = NULL;
588 tmp = xmalloc (sizeof (LBUFFER));
590 /* Input is always read into a fresh buffer. */
591 while (1)
593 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
594 if (n_read == 0 || n_read == SAFE_READ_ERROR)
595 break;
596 tmp->nbytes = n_read;
597 *read_pos += n_read;
598 tmp->nlines = 0;
599 tmp->next = NULL;
601 /* Count the number of newlines just read. */
603 char const *buffer_end = tmp->buffer + n_read;
604 char const *p = tmp->buffer;
605 while ((p = memchr (p, line_end, buffer_end - p)))
607 ++p;
608 ++tmp->nlines;
611 total_lines += tmp->nlines;
613 /* If there is enough room in the last buffer read, just append the new
614 one to it. This is because when reading from a pipe, 'n_read' can
615 often be very small. */
616 if (tmp->nbytes + last->nbytes < BUFSIZ)
618 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
619 last->nbytes += tmp->nbytes;
620 last->nlines += tmp->nlines;
622 else
624 /* If there's not enough room, link the new buffer onto the end of
625 the list, then either free up the oldest buffer for the next
626 read if that would leave enough lines, or else malloc a new one.
627 Some compaction mechanism is possible but probably not
628 worthwhile. */
629 last = last->next = tmp;
630 if (total_lines - first->nlines > n_lines)
632 tmp = first;
633 total_lines -= first->nlines;
634 first = first->next;
636 else
637 tmp = xmalloc (sizeof (LBUFFER));
641 free (tmp);
643 if (n_read == SAFE_READ_ERROR)
645 error (0, errno, _("error reading %s"), quoteaf (pretty_filename));
646 ok = false;
647 goto free_lbuffers;
650 /* If the file is empty, then bail out. */
651 if (last->nbytes == 0)
652 goto free_lbuffers;
654 /* This prevents a core dump when the pipe contains no newlines. */
655 if (n_lines == 0)
656 goto free_lbuffers;
658 /* Count the incomplete line on files that don't end with a newline. */
659 if (last->buffer[last->nbytes - 1] != line_end)
661 ++last->nlines;
662 ++total_lines;
665 /* Run through the list, printing lines. First, skip over unneeded
666 buffers. */
667 for (tmp = first; total_lines - tmp->nlines > n_lines; tmp = tmp->next)
668 total_lines -= tmp->nlines;
670 /* Find the correct beginning, then print the rest of the file. */
672 char const *beg = tmp->buffer;
673 char const *buffer_end = tmp->buffer + tmp->nbytes;
674 if (total_lines > n_lines)
676 /* Skip 'total_lines' - 'n_lines' newlines. We made sure that
677 'total_lines' - 'n_lines' <= 'tmp->nlines'. */
678 size_t j;
679 for (j = total_lines - n_lines; j; --j)
681 beg = memchr (beg, line_end, buffer_end - beg);
682 assert (beg);
683 ++beg;
687 xwrite_stdout (beg, buffer_end - beg);
690 for (tmp = tmp->next; tmp; tmp = tmp->next)
691 xwrite_stdout (tmp->buffer, tmp->nbytes);
693 free_lbuffers:
694 while (first)
696 tmp = first->next;
697 free (first);
698 first = tmp;
700 return ok;
703 /* Print the last N_BYTES characters from the end of pipe FD.
704 This is a stripped down version of pipe_lines.
705 Return true if successful. */
707 static bool
708 pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
709 uintmax_t *read_pos)
711 struct charbuffer
713 char buffer[BUFSIZ];
714 size_t nbytes;
715 struct charbuffer *next;
717 typedef struct charbuffer CBUFFER;
718 CBUFFER *first, *last, *tmp;
719 size_t i; /* Index into buffers. */
720 size_t total_bytes = 0; /* Total characters in all buffers. */
721 bool ok = true;
722 size_t n_read;
724 first = last = xmalloc (sizeof (CBUFFER));
725 first->nbytes = 0;
726 first->next = NULL;
727 tmp = xmalloc (sizeof (CBUFFER));
729 /* Input is always read into a fresh buffer. */
730 while (1)
732 n_read = safe_read (fd, tmp->buffer, BUFSIZ);
733 if (n_read == 0 || n_read == SAFE_READ_ERROR)
734 break;
735 *read_pos += n_read;
736 tmp->nbytes = n_read;
737 tmp->next = NULL;
739 total_bytes += tmp->nbytes;
740 /* If there is enough room in the last buffer read, just append the new
741 one to it. This is because when reading from a pipe, 'nbytes' can
742 often be very small. */
743 if (tmp->nbytes + last->nbytes < BUFSIZ)
745 memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes);
746 last->nbytes += tmp->nbytes;
748 else
750 /* If there's not enough room, link the new buffer onto the end of
751 the list, then either free up the oldest buffer for the next
752 read if that would leave enough characters, or else malloc a new
753 one. Some compaction mechanism is possible but probably not
754 worthwhile. */
755 last = last->next = tmp;
756 if (total_bytes - first->nbytes > n_bytes)
758 tmp = first;
759 total_bytes -= first->nbytes;
760 first = first->next;
762 else
764 tmp = xmalloc (sizeof (CBUFFER));
769 free (tmp);
771 if (n_read == SAFE_READ_ERROR)
773 error (0, errno, _("error reading %s"), quoteaf (pretty_filename));
774 ok = false;
775 goto free_cbuffers;
778 /* Run through the list, printing characters. First, skip over unneeded
779 buffers. */
780 for (tmp = first; total_bytes - tmp->nbytes > n_bytes; tmp = tmp->next)
781 total_bytes -= tmp->nbytes;
783 /* Find the correct beginning, then print the rest of the file.
784 We made sure that 'total_bytes' - 'n_bytes' <= 'tmp->nbytes'. */
785 if (total_bytes > n_bytes)
786 i = total_bytes - n_bytes;
787 else
788 i = 0;
789 xwrite_stdout (&tmp->buffer[i], tmp->nbytes - i);
791 for (tmp = tmp->next; tmp; tmp = tmp->next)
792 xwrite_stdout (tmp->buffer, tmp->nbytes);
794 free_cbuffers:
795 while (first)
797 tmp = first->next;
798 free (first);
799 first = tmp;
801 return ok;
804 /* Skip N_BYTES characters from the start of pipe FD, and print
805 any extra characters that were read beyond that.
806 Return 1 on error, 0 if ok, -1 if EOF. */
808 static int
809 start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
810 uintmax_t *read_pos)
812 char buffer[BUFSIZ];
814 while (0 < n_bytes)
816 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
817 if (bytes_read == 0)
818 return -1;
819 if (bytes_read == SAFE_READ_ERROR)
821 error (0, errno, _("error reading %s"), quoteaf (pretty_filename));
822 return 1;
824 *read_pos += bytes_read;
825 if (bytes_read <= n_bytes)
826 n_bytes -= bytes_read;
827 else
829 size_t n_remaining = bytes_read - n_bytes;
830 if (n_remaining)
831 xwrite_stdout (&buffer[n_bytes], n_remaining);
832 break;
836 return 0;
839 /* Skip N_LINES lines at the start of file or pipe FD, and print
840 any extra characters that were read beyond that.
841 Return 1 on error, 0 if ok, -1 if EOF. */
843 static int
844 start_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
845 uintmax_t *read_pos)
847 if (n_lines == 0)
848 return 0;
850 while (1)
852 char buffer[BUFSIZ];
853 size_t bytes_read = safe_read (fd, buffer, BUFSIZ);
854 if (bytes_read == 0) /* EOF */
855 return -1;
856 if (bytes_read == SAFE_READ_ERROR) /* error */
858 error (0, errno, _("error reading %s"), quoteaf (pretty_filename));
859 return 1;
862 char *buffer_end = buffer + bytes_read;
864 *read_pos += bytes_read;
866 char *p = buffer;
867 while ((p = memchr (p, line_end, buffer_end - p)))
869 ++p;
870 if (--n_lines == 0)
872 if (p < buffer_end)
873 xwrite_stdout (p, buffer_end - p);
874 return 0;
880 #if HAVE_INOTIFY
881 /* Without inotify support, always return false. Otherwise, return false
882 when FD is open on a file known to reside on a local file system.
883 If fstatfs fails, give a diagnostic and return true.
884 If fstatfs cannot be called, return true. */
885 static bool
886 fremote (int fd, const char *name)
888 bool remote = true; /* be conservative (poll by default). */
890 # if HAVE_FSTATFS && HAVE_STRUCT_STATFS_F_TYPE && defined __linux__
891 struct statfs buf;
892 int err = fstatfs (fd, &buf);
893 if (err != 0)
895 /* On at least linux-2.6.38, fstatfs fails with ENOSYS when FD
896 is open on a pipe. Treat that like a remote file. */
897 if (errno != ENOSYS)
898 error (0, errno, _("cannot determine location of %s. "
899 "reverting to polling"), quoteaf (name));
901 else
903 switch (is_local_fs_type (buf.f_type))
905 case 0:
906 break;
907 case -1:
908 /* Treat unrecognized file systems as "remote", so caller polls.
909 Note README-release has instructions for syncing the internal
910 list with the latest Linux kernel file system constants. */
911 break;
912 case 1:
913 remote = false;
914 break;
915 default:
916 assert (!"unexpected return value from is_local_fs_type");
919 # endif
921 return remote;
923 #else
924 /* Without inotify support, whether a file is remote is irrelevant.
925 Always return "false" in that case. */
926 # define fremote(fd, name) false
927 #endif
929 /* open/fstat F->name and handle changes. */
930 static void
931 recheck (struct File_spec *f, bool blocking)
933 struct stat new_stats;
934 bool ok = true;
935 bool is_stdin = (STREQ (f->name, "-"));
936 bool was_tailable = f->tailable;
937 int prev_errnum = f->errnum;
938 bool new_file;
939 int fd = (is_stdin
940 ? STDIN_FILENO
941 : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK)));
943 assert (valid_file_spec (f));
945 /* If the open fails because the file doesn't exist,
946 then mark the file as not tailable. */
947 f->tailable = !(reopen_inaccessible_files && fd == -1);
949 if (! disable_inotify && ! lstat (f->name, &new_stats)
950 && S_ISLNK (new_stats.st_mode))
952 /* Diagnose the edge case where a regular file is changed
953 to a symlink. We avoid inotify with symlinks since
954 it's awkward to match between symlink name and target. */
955 ok = false;
956 f->errnum = -1;
957 f->ignore = true;
959 error (0, 0, _("%s has been replaced with a symbolic link. "
960 "giving up on this name"), quoteaf (pretty_name (f)));
962 else if (fd == -1 || fstat (fd, &new_stats) < 0)
964 ok = false;
965 f->errnum = errno;
966 if (!f->tailable)
968 if (was_tailable)
970 /* FIXME-maybe: detect the case in which the file first becomes
971 unreadable (perms), and later becomes readable again and can
972 be seen to be the same file (dev/ino). Otherwise, tail prints
973 the entire contents of the file when it becomes readable. */
974 error (0, f->errnum, _("%s has become inaccessible"),
975 quoteaf (pretty_name (f)));
977 else
979 /* say nothing... it's still not tailable */
982 else if (prev_errnum != errno)
983 error (0, errno, "%s", quotef (pretty_name (f)));
985 else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode))
987 ok = false;
988 f->errnum = -1;
989 error (0, 0, _("%s has been replaced with an untailable file;\
990 giving up on this name"),
991 quoteaf (pretty_name (f)));
992 f->ignore = true;
994 else if (!disable_inotify && fremote (fd, pretty_name (f)))
996 ok = false;
997 f->errnum = -1;
998 error (0, 0, _("%s has been replaced with a remote file. "
999 "giving up on this name"), quoteaf (pretty_name (f)));
1000 f->ignore = true;
1001 f->remote = true;
1003 else
1005 f->errnum = 0;
1008 new_file = false;
1009 if (!ok)
1011 close_fd (fd, pretty_name (f));
1012 close_fd (f->fd, pretty_name (f));
1013 f->fd = -1;
1015 else if (prev_errnum && prev_errnum != ENOENT)
1017 new_file = true;
1018 assert (f->fd == -1);
1019 error (0, 0, _("%s has become accessible"), quoteaf (pretty_name (f)));
1021 else if (f->fd == -1)
1023 /* A new file even when inodes haven't changed as <dev,inode>
1024 pairs can be reused, and we know the file was missing
1025 on the previous iteration. Note this also means the file
1026 is redisplayed in --follow=name mode if renamed away from
1027 and back to a monitored name. */
1028 new_file = true;
1030 error (0, 0,
1031 _("%s has appeared; following new file"),
1032 quoteaf (pretty_name (f)));
1034 else if (f->ino != new_stats.st_ino || f->dev != new_stats.st_dev)
1036 /* File has been replaced (e.g., via log rotation) --
1037 tail the new one. */
1038 new_file = true;
1040 error (0, 0,
1041 _("%s has been replaced; following new file"),
1042 quoteaf (pretty_name (f)));
1044 /* Close the old one. */
1045 close_fd (f->fd, pretty_name (f));
1048 else
1050 /* No changes detected, so close new fd. */
1051 close_fd (fd, pretty_name (f));
1054 /* FIXME: When a log is rotated, daemons tend to log to the
1055 old file descriptor until the new file is present and
1056 the daemon is sent a signal. Therefore tail may miss entries
1057 being written to the old file. Perhaps we should keep
1058 the older file open and continue to monitor it until
1059 data is written to a new file. */
1060 if (new_file)
1062 /* Start at the beginning of the file. */
1063 record_open_fd (f, fd, 0, &new_stats, (is_stdin ? -1 : blocking));
1064 xlseek (fd, 0, SEEK_SET, pretty_name (f));
1068 /* Return true if any of the N_FILES files in F are live, i.e., have
1069 open file descriptors, or should be checked again (see --retry).
1070 When following descriptors, checking should only continue when any
1071 of the files is not yet ignored. */
1073 static bool
1074 any_live_files (const struct File_spec *f, size_t n_files)
1076 size_t i;
1078 if (reopen_inaccessible_files && follow_mode == Follow_name)
1079 return true; /* continue following for -F option */
1081 for (i = 0; i < n_files; i++)
1083 if (0 <= f[i].fd)
1085 return true;
1087 else
1089 if (reopen_inaccessible_files && follow_mode == Follow_descriptor)
1090 if (! f[i].ignore)
1091 return true;
1095 return false;
1098 /* Tail N_FILES files forever, or until killed.
1099 The pertinent information for each file is stored in an entry of F.
1100 Loop over each of them, doing an fstat to see if they have changed size,
1101 and an occasional open/fstat to see if any dev/ino pair has changed.
1102 If none of them have changed size in one iteration, sleep for a
1103 while and try again. Continue until the user interrupts us. */
1105 static void
1106 tail_forever (struct File_spec *f, size_t n_files, double sleep_interval)
1108 /* Use blocking I/O as an optimization, when it's easy. */
1109 bool blocking = (pid == 0 && follow_mode == Follow_descriptor
1110 && n_files == 1 && ! S_ISREG (f[0].mode));
1111 size_t last;
1112 bool writer_is_dead = false;
1114 last = n_files - 1;
1116 while (1)
1118 size_t i;
1119 bool any_input = false;
1121 for (i = 0; i < n_files; i++)
1123 int fd;
1124 char const *name;
1125 mode_t mode;
1126 struct stat stats;
1127 uintmax_t bytes_read;
1129 if (f[i].ignore)
1130 continue;
1132 if (f[i].fd < 0)
1134 recheck (&f[i], blocking);
1135 continue;
1138 fd = f[i].fd;
1139 name = pretty_name (&f[i]);
1140 mode = f[i].mode;
1142 if (f[i].blocking != blocking)
1144 int old_flags = fcntl (fd, F_GETFL);
1145 int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK);
1146 if (old_flags < 0
1147 || (new_flags != old_flags
1148 && fcntl (fd, F_SETFL, new_flags) == -1))
1150 /* Don't update f[i].blocking if fcntl fails. */
1151 if (S_ISREG (f[i].mode) && errno == EPERM)
1153 /* This happens when using tail -f on a file with
1154 the append-only attribute. */
1156 else
1157 error (EXIT_FAILURE, errno,
1158 _("%s: cannot change nonblocking mode"),
1159 quotef (name));
1161 else
1162 f[i].blocking = blocking;
1165 if (!f[i].blocking)
1167 if (fstat (fd, &stats) != 0)
1169 f[i].fd = -1;
1170 f[i].errnum = errno;
1171 error (0, errno, "%s", quotef (name));
1172 close (fd); /* ignore failure */
1173 continue;
1176 if (f[i].mode == stats.st_mode
1177 && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size)
1178 && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0)
1180 if ((max_n_unchanged_stats_between_opens
1181 <= f[i].n_unchanged_stats++)
1182 && follow_mode == Follow_name)
1184 recheck (&f[i], f[i].blocking);
1185 f[i].n_unchanged_stats = 0;
1187 continue;
1190 /* This file has changed. Print out what we can, and
1191 then keep looping. */
1193 f[i].mtime = get_stat_mtime (&stats);
1194 f[i].mode = stats.st_mode;
1196 /* reset counter */
1197 f[i].n_unchanged_stats = 0;
1199 /* XXX: This is only a heuristic, as the file may have also
1200 been truncated and written to if st_size >= size
1201 (in which case we ignore new data <= size). */
1202 if (S_ISREG (mode) && stats.st_size < f[i].size)
1204 error (0, 0, _("%s: file truncated"), quotef (name));
1205 /* Assume the file was truncated to 0,
1206 and therefore output all "new" data. */
1207 xlseek (fd, 0, SEEK_SET, name);
1208 f[i].size = 0;
1211 if (i != last)
1213 if (print_headers)
1214 write_header (name);
1215 last = i;
1219 bytes_read = dump_remainder (name, fd,
1220 (f[i].blocking
1221 ? COPY_A_BUFFER : COPY_TO_EOF));
1222 any_input |= (bytes_read != 0);
1223 f[i].size += bytes_read;
1226 if (! any_live_files (f, n_files))
1228 error (0, 0, _("no files remaining"));
1229 break;
1232 if ((!any_input || blocking) && fflush (stdout) != 0)
1233 error (EXIT_FAILURE, errno, _("write error"));
1235 /* If nothing was read, sleep and/or check for dead writers. */
1236 if (!any_input)
1238 if (writer_is_dead)
1239 break;
1241 /* Once the writer is dead, read the files once more to
1242 avoid a race condition. */
1243 writer_is_dead = (pid != 0
1244 && kill (pid, 0) != 0
1245 /* Handle the case in which you cannot send a
1246 signal to the writer, so kill fails and sets
1247 errno to EPERM. */
1248 && errno != EPERM);
1250 if (!writer_is_dead && xnanosleep (sleep_interval))
1251 error (EXIT_FAILURE, errno, _("cannot read realtime clock"));
1257 #if HAVE_INOTIFY
1259 /* Return true if any of the N_FILES files in F is remote, i.e., has
1260 an open file descriptor and is on a network file system. */
1262 static bool
1263 any_remote_file (const struct File_spec *f, size_t n_files)
1265 size_t i;
1267 for (i = 0; i < n_files; i++)
1268 if (0 <= f[i].fd && f[i].remote)
1269 return true;
1270 return false;
1273 /* Return true if any of the N_FILES files in F is a symlink.
1274 Note we don't worry about the edge case where "-" exists,
1275 since that will have the same consequences for inotify,
1276 which is the only context this function is currently used. */
1278 static bool
1279 any_symlinks (const struct File_spec *f, size_t n_files)
1281 size_t i;
1283 struct stat st;
1284 for (i = 0; i < n_files; i++)
1285 if (lstat (f[i].name, &st) == 0 && S_ISLNK (st.st_mode))
1286 return true;
1287 return false;
1290 /* Return true if any of the N_FILES files in F represents
1291 stdin and is tailable. */
1293 static bool
1294 tailable_stdin (const struct File_spec *f, size_t n_files)
1296 size_t i;
1298 for (i = 0; i < n_files; i++)
1299 if (!f[i].ignore && STREQ (f[i].name, "-"))
1300 return true;
1301 return false;
1304 static size_t
1305 wd_hasher (const void *entry, size_t tabsize)
1307 const struct File_spec *spec = entry;
1308 return spec->wd % tabsize;
1311 static bool
1312 wd_comparator (const void *e1, const void *e2)
1314 const struct File_spec *spec1 = e1;
1315 const struct File_spec *spec2 = e2;
1316 return spec1->wd == spec2->wd;
1319 /* Output (new) data for FSPEC->fd. */
1320 static void
1321 check_fspec (struct File_spec *fspec, struct File_spec **prev_fspec)
1323 struct stat stats;
1324 char const *name;
1326 if (fspec->fd == -1)
1327 return;
1329 name = pretty_name (fspec);
1331 if (fstat (fspec->fd, &stats) != 0)
1333 fspec->errnum = errno;
1334 close_fd (fspec->fd, name);
1335 fspec->fd = -1;
1336 return;
1339 /* XXX: This is only a heuristic, as the file may have also
1340 been truncated and written to if st_size >= size
1341 (in which case we ignore new data <= size).
1342 Though in the inotify case it's more likely we'll get
1343 separate events for truncate() and write(). */
1344 if (S_ISREG (fspec->mode) && stats.st_size < fspec->size)
1346 error (0, 0, _("%s: file truncated"), quotef (name));
1347 xlseek (fspec->fd, 0, SEEK_SET, name);
1348 fspec->size = 0;
1350 else if (S_ISREG (fspec->mode) && stats.st_size == fspec->size
1351 && timespec_cmp (fspec->mtime, get_stat_mtime (&stats)) == 0)
1352 return;
1354 if (fspec != *prev_fspec)
1356 if (print_headers)
1357 write_header (name);
1358 *prev_fspec = fspec;
1361 uintmax_t bytes_read = dump_remainder (name, fspec->fd, COPY_TO_EOF);
1362 fspec->size += bytes_read;
1364 if (fflush (stdout) != 0)
1365 error (EXIT_FAILURE, errno, _("write error"));
1368 /* Attempt to tail N_FILES files forever, or until killed.
1369 Check modifications using the inotify events system.
1370 Return false on error, or true to revert to polling. */
1371 static bool
1372 tail_forever_inotify (int wd, struct File_spec *f, size_t n_files,
1373 double sleep_interval)
1375 # if TAIL_TEST_SLEEP
1376 /* Delay between open() and inotify_add_watch()
1377 to help trigger different cases. */
1378 xnanosleep (1000000);
1379 # endif
1380 unsigned int max_realloc = 3;
1382 /* Map an inotify watch descriptor to the name of the file it's watching. */
1383 Hash_table *wd_to_name;
1385 bool found_watchable_file = false;
1386 bool tailed_but_unwatchable = false;
1387 bool found_unwatchable_dir = false;
1388 bool no_inotify_resources = false;
1389 bool writer_is_dead = false;
1390 struct File_spec *prev_fspec;
1391 size_t evlen = 0;
1392 char *evbuf;
1393 size_t evbuf_off = 0;
1394 size_t len = 0;
1396 wd_to_name = hash_initialize (n_files, NULL, wd_hasher, wd_comparator, NULL);
1397 if (! wd_to_name)
1398 xalloc_die ();
1400 /* The events mask used with inotify on files (not directories). */
1401 uint32_t inotify_wd_mask = IN_MODIFY;
1402 /* TODO: Perhaps monitor these events in Follow_descriptor mode also,
1403 to tag reported file names with "deleted", "moved" etc. */
1404 if (follow_mode == Follow_name)
1405 inotify_wd_mask |= (IN_ATTRIB | IN_DELETE_SELF | IN_MOVE_SELF);
1407 /* Add an inotify watch for each watched file. If -F is specified then watch
1408 its parent directory too, in this way when they re-appear we can add them
1409 again to the watch list. */
1410 size_t i;
1411 for (i = 0; i < n_files; i++)
1413 if (!f[i].ignore)
1415 size_t fnlen = strlen (f[i].name);
1416 if (evlen < fnlen)
1417 evlen = fnlen;
1419 f[i].wd = -1;
1421 if (follow_mode == Follow_name)
1423 size_t dirlen = dir_len (f[i].name);
1424 char prev = f[i].name[dirlen];
1425 f[i].basename_start = last_component (f[i].name) - f[i].name;
1427 f[i].name[dirlen] = '\0';
1429 /* It's fine to add the same directory more than once.
1430 In that case the same watch descriptor is returned. */
1431 f[i].parent_wd = inotify_add_watch (wd, dirlen ? f[i].name : ".",
1432 (IN_CREATE | IN_DELETE
1433 | IN_MOVED_TO | IN_ATTRIB));
1435 f[i].name[dirlen] = prev;
1437 if (f[i].parent_wd < 0)
1439 if (errno != ENOSPC) /* suppress confusing error. */
1440 error (0, errno, _("cannot watch parent directory of %s"),
1441 quoteaf (f[i].name));
1442 else
1443 error (0, 0, _("inotify resources exhausted"));
1444 found_unwatchable_dir = true;
1445 /* We revert to polling below. Note invalid uses
1446 of the inotify API will still be diagnosed. */
1447 break;
1451 f[i].wd = inotify_add_watch (wd, f[i].name, inotify_wd_mask);
1453 if (f[i].wd < 0)
1455 if (f[i].fd != -1) /* already tailed. */
1456 tailed_but_unwatchable = true;
1457 if (errno == ENOSPC || errno == ENOMEM)
1459 no_inotify_resources = true;
1460 error (0, 0, _("inotify resources exhausted"));
1461 break;
1463 else if (errno != f[i].errnum)
1464 error (0, errno, _("cannot watch %s"), quoteaf (f[i].name));
1465 continue;
1468 if (hash_insert (wd_to_name, &(f[i])) == NULL)
1469 xalloc_die ();
1471 found_watchable_file = true;
1475 /* Linux kernel 2.6.24 at least has a bug where eventually, ENOSPC is always
1476 returned by inotify_add_watch. In any case we should revert to polling
1477 when there are no inotify resources. Also a specified directory may not
1478 be currently present or accessible, so revert to polling. Also an already
1479 tailed but unwatchable due rename/unlink race, should also revert. */
1480 if (no_inotify_resources || found_unwatchable_dir
1481 || (follow_mode == Follow_descriptor && tailed_but_unwatchable))
1483 hash_free (wd_to_name);
1485 errno = 0;
1486 return true;
1488 if (follow_mode == Follow_descriptor && !found_watchable_file)
1489 return false;
1491 prev_fspec = &(f[n_files - 1]);
1493 /* Check files again. New files or data can be available since last time we
1494 checked and before they are watched by inotify. */
1495 for (i = 0; i < n_files; i++)
1497 if (! f[i].ignore)
1499 /* check for new files. */
1500 if (follow_mode == Follow_name)
1501 recheck (&(f[i]), false);
1502 else if (f[i].fd != -1)
1504 /* If the file was replaced in the small window since we tailed,
1505 then assume the watch is on the wrong item (different to
1506 that we've already produced output for), and so revert to
1507 polling the original descriptor. */
1508 struct stat stats;
1510 if (stat (f[i].name, &stats) == 0
1511 && (f[i].dev != stats.st_dev || f[i].ino != stats.st_ino))
1513 error (0, errno, _("%s was replaced"),
1514 quoteaf (pretty_name (&(f[i]))));
1515 hash_free (wd_to_name);
1517 errno = 0;
1518 return true;
1522 /* check for new data. */
1523 check_fspec (&f[i], &prev_fspec);
1527 evlen += sizeof (struct inotify_event) + 1;
1528 evbuf = xmalloc (evlen);
1530 /* Wait for inotify events and handle them. Events on directories
1531 ensure that watched files can be re-added when following by name.
1532 This loop blocks on the 'safe_read' call until a new event is notified.
1533 But when --pid=P is specified, tail usually waits via the select. */
1534 while (1)
1536 struct File_spec *fspec;
1537 struct inotify_event *ev;
1538 void *void_ev;
1540 /* When following by name without --retry, and the last file has
1541 been unlinked or renamed-away, diagnose it and return. */
1542 if (follow_mode == Follow_name
1543 && ! reopen_inaccessible_files
1544 && hash_get_n_entries (wd_to_name) == 0)
1546 error (0, 0, _("no files remaining"));
1547 return false;
1550 /* When watching a PID, ensure that a read from WD will not block
1551 indefinitely. */
1552 if (pid)
1554 if (writer_is_dead)
1555 exit (EXIT_SUCCESS);
1557 writer_is_dead = (kill (pid, 0) != 0 && errno != EPERM);
1559 struct timeval delay; /* how long to wait for file changes. */
1560 if (writer_is_dead)
1561 delay.tv_sec = delay.tv_usec = 0;
1562 else
1564 delay.tv_sec = (time_t) sleep_interval;
1565 delay.tv_usec = 1000000 * (sleep_interval - delay.tv_sec);
1568 fd_set rfd;
1569 FD_ZERO (&rfd);
1570 FD_SET (wd, &rfd);
1572 int file_change = select (wd + 1, &rfd, NULL, NULL, &delay);
1574 if (file_change == 0)
1575 continue;
1576 else if (file_change == -1)
1577 error (EXIT_FAILURE, errno, _("error monitoring inotify event"));
1580 if (len <= evbuf_off)
1582 len = safe_read (wd, evbuf, evlen);
1583 evbuf_off = 0;
1585 /* For kernels prior to 2.6.21, read returns 0 when the buffer
1586 is too small. */
1587 if ((len == 0 || (len == SAFE_READ_ERROR && errno == EINVAL))
1588 && max_realloc--)
1590 len = 0;
1591 evlen *= 2;
1592 evbuf = xrealloc (evbuf, evlen);
1593 continue;
1596 if (len == 0 || len == SAFE_READ_ERROR)
1597 error (EXIT_FAILURE, errno, _("error reading inotify event"));
1600 void_ev = evbuf + evbuf_off;
1601 ev = void_ev;
1602 evbuf_off += sizeof (*ev) + ev->len;
1604 if (ev->len) /* event on ev->name in watched directory. */
1606 size_t j;
1607 for (j = 0; j < n_files; j++)
1609 /* With N=hundreds of frequently-changing files, this O(N^2)
1610 process might be a problem. FIXME: use a hash table? */
1611 if (f[j].parent_wd == ev->wd
1612 && STREQ (ev->name, f[j].name + f[j].basename_start))
1613 break;
1616 /* It is not a watched file. */
1617 if (j == n_files)
1618 continue;
1620 fspec = &(f[j]);
1622 int new_wd = -1;
1623 bool deleting = !! (ev->mask & IN_DELETE);
1625 if (! deleting)
1627 /* Adding the same inode again will look up any existing wd. */
1628 new_wd = inotify_add_watch (wd, f[j].name, inotify_wd_mask);
1631 if (! deleting && new_wd < 0)
1633 if (errno == ENOSPC || errno == ENOMEM)
1635 error (0, 0, _("inotify resources exhausted"));
1636 hash_free (wd_to_name);
1637 errno = 0;
1638 return true; /* revert to polling. */
1640 else
1642 /* Can get ENOENT for a dangling symlink for example. */
1643 error (0, errno, _("cannot watch %s"), quoteaf (f[j].name));
1645 /* We'll continue below after removing the existing watch. */
1648 /* This will be false if only attributes of file change. */
1649 bool new_watch;
1650 new_watch = (! deleting) && (fspec->wd < 0 || new_wd != fspec->wd);
1652 if (new_watch)
1654 if (0 <= fspec->wd)
1656 inotify_rm_watch (wd, fspec->wd);
1657 hash_delete (wd_to_name, fspec);
1660 fspec->wd = new_wd;
1662 if (new_wd == -1)
1663 continue;
1665 /* If the file was moved then inotify will use the source file wd
1666 for the destination file. Make sure the key is not present in
1667 the table. */
1668 struct File_spec *prev = hash_delete (wd_to_name, fspec);
1669 if (prev && prev != fspec)
1671 if (follow_mode == Follow_name)
1672 recheck (prev, false);
1673 prev->wd = -1;
1674 close_fd (prev->fd, pretty_name (prev));
1677 if (hash_insert (wd_to_name, fspec) == NULL)
1678 xalloc_die ();
1681 if (follow_mode == Follow_name)
1682 recheck (fspec, false);
1684 else
1686 struct File_spec key;
1687 key.wd = ev->wd;
1688 fspec = hash_lookup (wd_to_name, &key);
1691 if (! fspec)
1692 continue;
1694 if (ev->mask & (IN_ATTRIB | IN_DELETE | IN_DELETE_SELF | IN_MOVE_SELF))
1696 /* Note for IN_MOVE_SELF (the file we're watching has
1697 been clobbered via a rename) we leave the watch
1698 in place since it may still be part of the set
1699 of watched names. */
1700 if (ev->mask & IN_DELETE_SELF)
1702 inotify_rm_watch (wd, fspec->wd);
1703 hash_delete (wd_to_name, fspec);
1706 /* Note we get IN_ATTRIB for unlink() as st_nlink decrements.
1707 The usual path is a close() done in recheck() triggers
1708 an IN_DELETE_SELF event as the inode is removed.
1709 However sometimes open() will succeed as even though
1710 st_nlink is decremented, the dentry (cache) is not updated.
1711 Thus we depend on the IN_DELETE event on the directory
1712 to trigger processing for the removed file. */
1714 recheck (fspec, false);
1716 continue;
1718 check_fspec (fspec, &prev_fspec);
1721 #endif
1723 /* Output the last N_BYTES bytes of file FILENAME open for reading in FD.
1724 Return true if successful. */
1726 static bool
1727 tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes,
1728 uintmax_t *read_pos)
1730 struct stat stats;
1732 if (fstat (fd, &stats))
1734 error (0, errno, _("cannot fstat %s"), quoteaf (pretty_filename));
1735 return false;
1738 if (from_start)
1740 if ( ! presume_input_pipe
1741 && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX)
1743 xlseek (fd, n_bytes, SEEK_CUR, pretty_filename);
1744 *read_pos += n_bytes;
1746 else
1748 int t = start_bytes (pretty_filename, fd, n_bytes, read_pos);
1749 if (t)
1750 return t < 0;
1752 n_bytes = COPY_TO_EOF;
1754 else
1756 off_t end_pos = ((! presume_input_pipe && usable_st_size (&stats)
1757 && n_bytes <= OFF_T_MAX)
1758 ? stats.st_size : -1);
1759 if (end_pos <= ST_BLKSIZE (stats))
1760 return pipe_bytes (pretty_filename, fd, n_bytes, read_pos);
1761 off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename);
1762 if (current_pos < end_pos)
1764 off_t bytes_remaining = end_pos - current_pos;
1766 if (n_bytes < bytes_remaining)
1768 current_pos = end_pos - n_bytes;
1769 xlseek (fd, current_pos, SEEK_SET, pretty_filename);
1772 *read_pos = current_pos;
1775 *read_pos += dump_remainder (pretty_filename, fd, n_bytes);
1776 return true;
1779 /* Output the last N_LINES lines of file FILENAME open for reading in FD.
1780 Return true if successful. */
1782 static bool
1783 tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines,
1784 uintmax_t *read_pos)
1786 struct stat stats;
1788 if (fstat (fd, &stats))
1790 error (0, errno, _("cannot fstat %s"), quoteaf (pretty_filename));
1791 return false;
1794 if (from_start)
1796 int t = start_lines (pretty_filename, fd, n_lines, read_pos);
1797 if (t)
1798 return t < 0;
1799 *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF);
1801 else
1803 off_t start_pos = -1;
1804 off_t end_pos;
1806 /* Use file_lines only if FD refers to a regular file for
1807 which lseek (... SEEK_END) works. */
1808 if ( ! presume_input_pipe
1809 && S_ISREG (stats.st_mode)
1810 && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1
1811 && start_pos < (end_pos = lseek (fd, 0, SEEK_END)))
1813 *read_pos = end_pos;
1814 if (end_pos != 0
1815 && ! file_lines (pretty_filename, fd, n_lines,
1816 start_pos, end_pos, read_pos))
1817 return false;
1819 else
1821 /* Under very unlikely circumstances, it is possible to reach
1822 this point after positioning the file pointer to end of file
1823 via the 'lseek (...SEEK_END)' above. In that case, reposition
1824 the file pointer back to start_pos before calling pipe_lines. */
1825 if (start_pos != -1)
1826 xlseek (fd, start_pos, SEEK_SET, pretty_filename);
1828 return pipe_lines (pretty_filename, fd, n_lines, read_pos);
1831 return true;
1834 /* Display the last N_UNITS units of file FILENAME, open for reading
1835 via FD. Set *READ_POS to the position of the input stream pointer.
1836 *READ_POS is usually the number of bytes read and corresponds to an
1837 offset from the beginning of a file. However, it may be larger than
1838 OFF_T_MAX (as for an input pipe), and may also be larger than the
1839 number of bytes read (when an input pointer is initially not at
1840 beginning of file), and may be far greater than the number of bytes
1841 actually read for an input file that is seekable.
1842 Return true if successful. */
1844 static bool
1845 tail (const char *filename, int fd, uintmax_t n_units,
1846 uintmax_t *read_pos)
1848 *read_pos = 0;
1849 if (count_lines)
1850 return tail_lines (filename, fd, n_units, read_pos);
1851 else
1852 return tail_bytes (filename, fd, n_units, read_pos);
1855 /* Display the last N_UNITS units of the file described by F.
1856 Return true if successful. */
1858 static bool
1859 tail_file (struct File_spec *f, uintmax_t n_units)
1861 int fd;
1862 bool ok;
1864 bool is_stdin = (STREQ (f->name, "-"));
1866 if (is_stdin)
1868 have_read_stdin = true;
1869 fd = STDIN_FILENO;
1870 if (O_BINARY && ! isatty (STDIN_FILENO))
1871 xfreopen (NULL, "rb", stdin);
1873 else
1874 fd = open (f->name, O_RDONLY | O_BINARY);
1876 f->tailable = !(reopen_inaccessible_files && fd == -1);
1878 if (fd == -1)
1880 if (forever)
1882 f->fd = -1;
1883 f->errnum = errno;
1884 f->ignore = false;
1885 f->ino = 0;
1886 f->dev = 0;
1888 error (0, errno, _("cannot open %s for reading"),
1889 quoteaf (pretty_name (f)));
1890 ok = false;
1892 else
1894 uintmax_t read_pos;
1896 if (print_headers)
1897 write_header (pretty_name (f));
1898 ok = tail (pretty_name (f), fd, n_units, &read_pos);
1899 if (forever)
1901 struct stat stats;
1903 #if TAIL_TEST_SLEEP
1904 /* Before the tail function provided 'read_pos', there was
1905 a race condition described in the URL below. This sleep
1906 call made the window big enough to exercise the problem. */
1907 xnanosleep (1);
1908 #endif
1909 f->errnum = ok - 1;
1910 if (fstat (fd, &stats) < 0)
1912 ok = false;
1913 f->errnum = errno;
1914 error (0, errno, _("error reading %s"),
1915 quoteaf (pretty_name (f)));
1917 else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode))
1919 error (0, 0, _("%s: cannot follow end of this type of file;\
1920 giving up on this name"),
1921 quotef (pretty_name (f)));
1922 ok = false;
1923 f->errnum = -1;
1924 f->ignore = true;
1927 if (!ok)
1929 close_fd (fd, pretty_name (f));
1930 f->fd = -1;
1932 else
1934 /* Note: we must use read_pos here, not stats.st_size,
1935 to avoid a race condition described by Ken Raeburn:
1936 http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */
1937 record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1));
1938 f->remote = fremote (fd, pretty_name (f));
1941 else
1943 if (!is_stdin && close (fd))
1945 error (0, errno, _("error reading %s"),
1946 quoteaf (pretty_name (f)));
1947 ok = false;
1952 return ok;
1955 /* If obsolete usage is allowed, and the command line arguments are of
1956 the obsolete form and the option string is well-formed, set
1957 *N_UNITS, the globals COUNT_LINES, FOREVER, and FROM_START, and
1958 return true. If the command line arguments are obviously incorrect
1959 (e.g., because obsolete usage is not allowed and the arguments are
1960 incorrect for non-obsolete usage), report an error and exit.
1961 Otherwise, return false and don't modify any parameter or global
1962 variable. */
1964 static bool
1965 parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units)
1967 const char *p;
1968 const char *n_string;
1969 const char *n_string_end;
1970 bool obsolete_usage;
1971 int default_count = DEFAULT_N_LINES;
1972 bool t_from_start;
1973 bool t_count_lines = true;
1974 bool t_forever = false;
1976 /* With the obsolete form, there is one option string and at most
1977 one file argument. Watch out for "-" and "--", though. */
1978 if (! (argc == 2
1979 || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1]))
1980 || (3 <= argc && argc <= 4 && STREQ (argv[2], "--"))))
1981 return false;
1983 obsolete_usage = (posix2_version () < 200112);
1984 p = argv[1];
1986 switch (*p++)
1988 default:
1989 return false;
1991 case '+':
1992 /* Leading "+" is a file name in the non-obsolete form. */
1993 if (!obsolete_usage)
1994 return false;
1996 t_from_start = true;
1997 break;
1999 case '-':
2000 /* In the non-obsolete form, "-" is standard input and "-c"
2001 requires an option-argument. The obsolete multidigit options
2002 are supported as a GNU extension even when conforming to
2003 POSIX 1003.1-2001, so don't complain about them. */
2004 if (!obsolete_usage && !p[p[0] == 'c'])
2005 return false;
2007 t_from_start = false;
2008 break;
2011 n_string = p;
2012 while (ISDIGIT (*p))
2013 p++;
2014 n_string_end = p;
2016 switch (*p)
2018 case 'b': default_count *= 512; /* Fall through. */
2019 case 'c': t_count_lines = false; /* Fall through. */
2020 case 'l': p++; break;
2023 if (*p == 'f')
2025 t_forever = true;
2026 ++p;
2029 if (*p)
2030 return false;
2032 if (n_string == n_string_end)
2033 *n_units = default_count;
2034 else if ((xstrtoumax (n_string, NULL, 10, n_units, "b")
2035 & ~LONGINT_INVALID_SUFFIX_CHAR)
2036 != LONGINT_OK)
2038 error (EXIT_FAILURE, errno, "%s: %s", _("invalid number"),
2039 quote (argv[1]));
2042 /* Set globals. */
2043 from_start = t_from_start;
2044 count_lines = t_count_lines;
2045 forever = t_forever;
2047 return true;
2050 static void
2051 parse_options (int argc, char **argv,
2052 uintmax_t *n_units, enum header_mode *header_mode,
2053 double *sleep_interval)
2055 int c;
2057 while ((c = getopt_long (argc, argv, "c:n:fFqs:vz0123456789",
2058 long_options, NULL))
2059 != -1)
2061 switch (c)
2063 case 'F':
2064 forever = true;
2065 follow_mode = Follow_name;
2066 reopen_inaccessible_files = true;
2067 break;
2069 case 'c':
2070 case 'n':
2071 count_lines = (c == 'n');
2072 if (*optarg == '+')
2073 from_start = true;
2074 else if (*optarg == '-')
2075 ++optarg;
2077 *n_units = xdectoumax (optarg, 0, UINTMAX_MAX, "bkKmMGTPEZY0",
2078 count_lines
2079 ? _("invalid number of lines")
2080 : _("invalid number of bytes"), 0);
2081 break;
2083 case 'f':
2084 case LONG_FOLLOW_OPTION:
2085 forever = true;
2086 if (optarg == NULL)
2087 follow_mode = DEFAULT_FOLLOW_MODE;
2088 else
2089 follow_mode = XARGMATCH ("--follow", optarg,
2090 follow_mode_string, follow_mode_map);
2091 break;
2093 case RETRY_OPTION:
2094 reopen_inaccessible_files = true;
2095 break;
2097 case MAX_UNCHANGED_STATS_OPTION:
2098 /* --max-unchanged-stats=N */
2099 max_n_unchanged_stats_between_opens =
2100 xdectoumax (optarg, 0, UINTMAX_MAX, "",
2101 _("invalid maximum number of unchanged stats between opens"), 0);
2102 break;
2104 case DISABLE_INOTIFY_OPTION:
2105 disable_inotify = true;
2106 break;
2108 case PID_OPTION:
2109 pid = xdectoumax (optarg, 0, PID_T_MAX, "", _("invalid PID"), 0);
2110 break;
2112 case PRESUME_INPUT_PIPE_OPTION:
2113 presume_input_pipe = true;
2114 break;
2116 case 'q':
2117 *header_mode = never;
2118 break;
2120 case 's':
2122 double s;
2123 if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s))
2124 error (EXIT_FAILURE, 0,
2125 _("invalid number of seconds: %s"), quote (optarg));
2126 *sleep_interval = s;
2128 break;
2130 case 'v':
2131 *header_mode = always;
2132 break;
2134 case 'z':
2135 line_end = '\0';
2136 break;
2138 case_GETOPT_HELP_CHAR;
2140 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
2142 case '0': case '1': case '2': case '3': case '4':
2143 case '5': case '6': case '7': case '8': case '9':
2144 error (EXIT_FAILURE, 0,
2145 _("option used in invalid context -- %c"), c);
2147 default:
2148 usage (EXIT_FAILURE);
2152 if (reopen_inaccessible_files)
2154 if (!forever)
2156 reopen_inaccessible_files = false;
2157 error (0, 0, _("warning: --retry ignored; --retry is useful"
2158 " only when following"));
2160 else if (follow_mode == Follow_descriptor)
2161 error (0, 0, _("warning: --retry only effective for the initial open"));
2164 if (pid && !forever)
2165 error (0, 0,
2166 _("warning: PID ignored; --pid=PID is useful only when following"));
2167 else if (pid && kill (pid, 0) != 0 && errno == ENOSYS)
2169 error (0, 0, _("warning: --pid=PID is not supported on this system"));
2170 pid = 0;
2174 /* Mark as '.ignore'd each member of F that corresponds to a
2175 pipe or fifo, and return the number of non-ignored members. */
2176 static size_t
2177 ignore_fifo_and_pipe (struct File_spec *f, size_t n_files)
2179 /* When there is no FILE operand and stdin is a pipe or FIFO
2180 POSIX requires that tail ignore the -f option.
2181 Since we allow multiple FILE operands, we extend that to say: with -f,
2182 ignore any "-" operand that corresponds to a pipe or FIFO. */
2183 size_t n_viable = 0;
2185 size_t i;
2186 for (i = 0; i < n_files; i++)
2188 bool is_a_fifo_or_pipe =
2189 (STREQ (f[i].name, "-")
2190 && !f[i].ignore
2191 && 0 <= f[i].fd
2192 && (S_ISFIFO (f[i].mode)
2193 || (HAVE_FIFO_PIPES != 1 && isapipe (f[i].fd))));
2194 if (is_a_fifo_or_pipe)
2195 f[i].ignore = true;
2196 else
2197 ++n_viable;
2200 return n_viable;
2204 main (int argc, char **argv)
2206 enum header_mode header_mode = multiple_files;
2207 bool ok = true;
2208 /* If from_start, the number of items to skip before printing; otherwise,
2209 the number of items at the end of the file to print. Although the type
2210 is signed, the value is never negative. */
2211 uintmax_t n_units = DEFAULT_N_LINES;
2212 size_t n_files;
2213 char **file;
2214 struct File_spec *F;
2215 size_t i;
2216 bool obsolete_option;
2218 /* The number of seconds to sleep between iterations.
2219 During one iteration, every file name or descriptor is checked to
2220 see if it has changed. */
2221 double sleep_interval = 1.0;
2223 initialize_main (&argc, &argv);
2224 set_program_name (argv[0]);
2225 setlocale (LC_ALL, "");
2226 bindtextdomain (PACKAGE, LOCALEDIR);
2227 textdomain (PACKAGE);
2229 atexit (close_stdout);
2231 have_read_stdin = false;
2233 count_lines = true;
2234 forever = from_start = print_headers = false;
2235 line_end = '\n';
2236 obsolete_option = parse_obsolete_option (argc, argv, &n_units);
2237 argc -= obsolete_option;
2238 argv += obsolete_option;
2239 parse_options (argc, argv, &n_units, &header_mode, &sleep_interval);
2241 /* To start printing with item N_UNITS from the start of the file, skip
2242 N_UNITS - 1 items. 'tail -n +0' is actually meaningless, but for Unix
2243 compatibility it's treated the same as 'tail -n +1'. */
2244 if (from_start)
2246 if (n_units)
2247 --n_units;
2250 IF_LINT (assert (0 <= argc));
2252 if (optind < argc)
2254 n_files = argc - optind;
2255 file = argv + optind;
2257 else
2259 static char *dummy_stdin = (char *) "-";
2260 n_files = 1;
2261 file = &dummy_stdin;
2265 bool found_hyphen = false;
2267 for (i = 0; i < n_files; i++)
2268 if (STREQ (file[i], "-"))
2269 found_hyphen = true;
2271 /* When following by name, there must be a name. */
2272 if (found_hyphen && follow_mode == Follow_name)
2273 error (EXIT_FAILURE, 0, _("cannot follow %s by name"), quoteaf ("-"));
2275 /* When following forever, warn if any file is '-'.
2276 This is only a warning, since tail's output (before a failing seek,
2277 and that from any non-stdin files) might still be useful. */
2278 if (forever && found_hyphen && isatty (STDIN_FILENO))
2279 error (0, 0, _("warning: following standard input"
2280 " indefinitely is ineffective"));
2283 /* Don't read anything if we'll never output anything. */
2284 if (! n_units && ! forever && ! from_start)
2285 return EXIT_SUCCESS;
2287 F = xnmalloc (n_files, sizeof *F);
2288 for (i = 0; i < n_files; i++)
2289 F[i].name = file[i];
2291 if (header_mode == always
2292 || (header_mode == multiple_files && n_files > 1))
2293 print_headers = true;
2295 if (O_BINARY && ! isatty (STDOUT_FILENO))
2296 xfreopen (NULL, "wb", stdout);
2298 for (i = 0; i < n_files; i++)
2299 ok &= tail_file (&F[i], n_units);
2301 if (forever && ignore_fifo_and_pipe (F, n_files))
2303 #if HAVE_INOTIFY
2304 /* tailable_stdin() checks if the user specifies stdin via "-",
2305 or implicitly by providing no arguments. If so, we won't use inotify.
2306 Technically, on systems with a working /dev/stdin, we *could*,
2307 but would it be worth it? Verifying that it's a real device
2308 and hooked up to stdin is not trivial, while reverting to
2309 non-inotify-based tail_forever is easy and portable.
2311 any_remote_file() checks if the user has specified any
2312 files that reside on remote file systems. inotify is not used
2313 in this case because it would miss any updates to the file
2314 that were not initiated from the local system.
2316 any_symlinks() checks if the user has specified any symbolic links.
2317 inotify is not used in this case because it returns updated _targets_
2318 which would not match the specified names. If we tried to always
2319 use the target names, then we would miss changes to the symlink itself.
2321 ok is false when one of the files specified could not be opened for
2322 reading. In this case and when following by descriptor,
2323 tail_forever_inotify() cannot be used (in its current implementation).
2325 FIXME: inotify doesn't give any notification when a new
2326 (remote) file or directory is mounted on top a watched file.
2327 When follow_mode == Follow_name we would ideally like to detect that.
2328 Note if there is a change to the original file then we'll
2329 recheck it and follow the new file, or ignore it if the
2330 file has changed to being remote.
2332 FIXME: when using inotify, and a directory for a watched file
2333 is recreated, then we don't recheck any new file when
2334 follow_mode == Follow_name.
2336 FIXME-maybe: inotify has a watch descriptor per inode, and hence with
2337 our current hash implementation will only --follow data for one
2338 of the names when multiple hardlinked files are specified, or
2339 for one name when a name is specified multiple times. */
2340 if (!disable_inotify && (tailable_stdin (F, n_files)
2341 || any_remote_file (F, n_files)
2342 || any_symlinks (F, n_files)
2343 || (!ok && follow_mode == Follow_descriptor)))
2344 disable_inotify = true;
2346 if (!disable_inotify)
2348 int wd = inotify_init ();
2349 if (0 <= wd)
2351 /* Flush any output from tail_file, now, since
2352 tail_forever_inotify flushes only after writing,
2353 not before reading. */
2354 if (fflush (stdout) != 0)
2355 error (EXIT_FAILURE, errno, _("write error"));
2357 if (! tail_forever_inotify (wd, F, n_files, sleep_interval))
2358 return EXIT_FAILURE;
2360 error (0, errno, _("inotify cannot be used, reverting to polling"));
2362 /* Free resources as this process can be long lived,
2363 and we may have exhausted system resources above. */
2365 for (i = 0; i < n_files; i++)
2367 /* It's OK to remove the same watch multiple times,
2368 ignoring the EINVAL from redundant calls. */
2369 if (F[i].wd != -1)
2370 inotify_rm_watch (wd, F[i].wd);
2371 if (F[i].parent_wd != -1)
2372 inotify_rm_watch (wd, F[i].parent_wd);
2375 #endif
2376 disable_inotify = true;
2377 tail_forever (F, n_files, sleep_interval);
2380 IF_LINT (free (F));
2382 if (have_read_stdin && close (STDIN_FILENO) < 0)
2383 error (EXIT_FAILURE, errno, "-");
2384 return ok ? EXIT_SUCCESS : EXIT_FAILURE;