pax_global_header00006660000000000000000000000064106702333620014514gustar00rootroot0000000000000052 comment=a9b1b5e00a2df2081cf604977954f2db16db928b inotail-0.5/000077500000000000000000000000001067023336200130175ustar00rootroot00000000000000inotail-0.5/.gitignore000066400000000000000000000001001067023336200147760ustar00rootroot00000000000000# binary files *.o inotail inotify-watchdir # other cscope.out inotail-0.5/LICENSE000066400000000000000000000431031067023336200140250ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. inotail-0.5/Makefile000066400000000000000000000022321067023336200144560ustar00rootroot00000000000000# Makefile for inotail # # Copyright (C) 2006-2007 Tobias Klauser # # Licensed under the terms of the GNU General Public License; version 2 or later. VERSION = 0.5 # Paths prefix = /usr/local BINDIR = $(prefix)/bin MANDIR = $(prefix)/share/man/man1 CC := gcc CFLAGS := $(CFLAGS) -pipe -D_USE_SOURCE -DVERSION="\"$(VERSION)\"" -W -Wall \ -Wstrict-prototypes -Wsign-compare -Wshadow -Wchar-subscripts \ -Wmissing-declarations -Wpointer-arith -Wcast-align -Wmissing-prototypes # Compile with 'make DEBUG=true' to enable debugging DEBUG = false ifeq ($(strip $(DEBUG)),true) CFLAGS += -g -DDEBUG endif all: inotail inotail: inotail.o %.o: %.c %.h $(CC) $(CFLAGS) -c $< -o $@ install: inotail install -m 775 -D inotail $(BINDIR)/inotail install -m 644 -D inotail.1 $(MANDIR)/inotail.1 gzip -9 $(MANDIR)/inotail.1 uninstall: rm $(BINDIR)/inotail $(MANDIR)/inotail.1* cscope: cscope -b release: git-archive --format=tar --prefix=inotail-$(VERSION)/ HEAD | gzip -9v > ../inotail-$(VERSION).tar.gz git-archive --format=tar --prefix=inotail-$(VERSION)/ HEAD | bzip2 -9v > ../inotail-$(VERSION).tar.bz2 clean: rm -f inotail *.o cscope.* inotail-0.5/README000066400000000000000000000032521067023336200137010ustar00rootroot00000000000000 inotail - inotify enhanced tail o===============================o inotail is a replacement for the 'tail' program found in the base installation of every Linux/UNIX system. It makes use of the inotify infrastructure in recent versions of the Linux kernel to speed up tailing files in the follow mode (the '-f' option). Standard tail polls the file every second by default while inotail listens to special events sent by the kernel through the inotify API to determine whether a file needs to be reread. Currently inotail is not fully compatible to neither POSIX or GNU tail but might be in the future. Requirements ------------ - Linux kernel 2.6.13 or higher with CONFIG_INOTIFY enabled - Standard C Library (tested with GNU libc but might work with others too) - GCC (other compilers might work but are not tested) Building and installing inotail ------------------------------- To build inotail type: $ make By default, inotail is installed to /usr/local/bin/, the manpage is installed to /usr/local/share/man/man1/. To install the inotail files to these locations type: $ make install To change these locations just set the prefix variable. E.g. to install the inotail binary to /usr/ and the manpage to /usr/share/man/ respectively type: $ make prefix=/usr install License ------- inotail is licensed under the terms of the GNU General Public License version 2 or later. You can find the full text in the file LICENSE in the source tree of inotail. The files inotify.h and inotify-syscalls.h were taken from the source tree of the Linux kernel and slightly altered. Both are licensed under the terms of the GNU General Public License version 2. -- Tobias Klauser inotail-0.5/changelog000066400000000000000000000020101067023336200146620ustar00rootroot00000000000000inotail 0.5 * Output verbose file headers correctly when used in a pipe * Small code cleanups -- Tobias Klauser 2007-09-07 13:30 inotail 0.4 * Use dynamic buffers of optimal size (st_blksize in struct stat) for filesystem I/O (patch by Folkert van Heusden) * Added handling of EINTR/EAGAIN while watching files for changes (patch by Anthony Martinez) * Better error checking and handling (patch by Folkert van Heusden) * Various cleanups -- Tobias Klauser 2007-06-20 15:00 inotail 0.3 * Follow files even if they were moved * Fix a problem when tailing more than 4096 bytes/chars at once * Only print the filename once when the -v option is specified * Various small fixes and cleanups -- Tobias Klauser 2007-04-17 13:44 inotail 0.2 * Support for the -n/-c + options (tail relative to start of file) * Copyright and license cleanup * Various fixes -- Tobias Klauser 2006-11-30 17:56 inotail-0.5/inotail.1000066400000000000000000000036251067023336200145460ustar00rootroot00000000000000'\" t .\" ** The above line should force tbl to be a preprocessor ** .\" Man page for inotail .\" .\" Copyright (c) 2006 Tobias Klauser .\" .\" You may distribute under the terms of the GNU General Public .\" License as specified in the file COPYING that comes with .\" inotail. .pc .TH INOTAIL 1 "2006-08-13" "" "Inotify enhanced tail" .SH NAME inotail \- A fast and lightweight version of tail using inotify .SH SYNOPSIS .B inotail [OPTION]... [FILE]... .SH DESCRIPTION .B inotail is a replacement for the 'tail' program found in the base installation of every Linux/UNIX system. It makes use of the inotify infrastructure in recent versions of the Linux kernel to speed up tailing files in the follow mode (the '\-f' option). Standard tail polls the file every second by default while inotail listens to special events sent by the kernel through the inotify API to determine whether a file needs to be reread. \fINote:\fR inotail will not work on systems running a kernel without inotify. To enable inotify, please set CONFIG_INOTIFY=y in your Linux kernel configuration and recompile it. .PP Currently inotail is not fully compatible to neither POSIX or GNU tail but might be in the future. .SH OPTIONS .TP .B \-c \fIN\fR, \fB\-\-bytes\fR=\fIN\fR output the last N bytes. If the first character of N is a '+', begin printing with the Nth character from the start of each file. .TP .B \-f, \fB\-\-follow keep the file(s) open and print appended data as the file grows .TP .B \-n \fIN\fR, \fB\-\-lines\fR=\fIN\fR output the last N lines (default: 10) If the first character of N is a '+', begin printing with the Nth line from the start of each file. .TP .B \-v, \fB\-\-verbose print headers with file names .TP .B \-h, \fB\-\-help show help and exit .TP .B \-V, \fB\-\-version show inotail version and exit .SH AUTHOR .PP Written by Tobias Klauser .SH SEE ALSO .PP .BR tail(1), .BR inotify(7) inotail-0.5/inotail.c000066400000000000000000000313501067023336200146240ustar00rootroot00000000000000/* * inotail.c * A fast implementation of tail which uses the inotify API present in * recent versions of the Linux kernel. * * Copyright (C) 2005-2007, Tobias Klauser * * The idea was taken from turbotail. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 51 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #define _GNU_SOURCE #include #include #include #include #include #include #include #include #include #include "inotify.h" #include "inotify-syscalls.h" #include "inotail.h" #define PROGRAM_NAME "inotail" #define DEFAULT_BUFFER_SIZE 4096 /* inotify event buffer length for one file */ #define INOTIFY_BUFLEN (4 * sizeof(struct inotify_event)) /* Print header with filename before tailing the file? */ static char verbose = 0; /* Tailing relative to begin or end of file */ static char from_begin = 0; /* Number of ignored files */ static int n_ignored = 0; /* Command line options */ static const struct option long_opts[] = { { "bytes", required_argument, NULL, 'c' }, { "follow", optional_argument, NULL, 'f' }, { "lines", required_argument, NULL, 'n' }, { "verbose", no_argument, NULL, 'v' }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'V' }, { NULL, 0, NULL, 0 } }; static void *emalloc(size_t size) { void *ret = malloc(size); if (unlikely(!ret)) { fprintf(stderr, "Error: Failed to allocate %d bytes of memory (%s)\n", size, strerror(errno)); exit(EXIT_FAILURE); } return ret; } static void usage(const int status) { fprintf(stdout, "Usage: %s [OPTION]... [FILE]...\n\n" " -c N, --bytes=N output the last N bytes\n" " -f, --follow output as the file grows\n" " -n N, --lines=N output the last N lines (default: %d)\n" " -v, --verbose print headers with file names\n" " -h, --help show this help and exit\n" " -V, --version show version and exit\n\n" "If the first character of N (the number of bytes or lines) is a `+',\n" "begin printing with the Nth item from the start of each file, otherwise,\n" "print the last N items in the file.\n", PROGRAM_NAME, DEFAULT_N_LINES); exit(status); } static inline void setup_file(struct file_struct *f) { f->fd = f->i_watch = -1; f->size = 0; f->blksize = DEFAULT_BUFFER_SIZE; f->ignore = 0; } static void ignore_file(struct file_struct *f) { if (f->fd != -1) { close(f->fd); f->fd = -1; } f->ignore = 1; n_ignored++; } static inline char *pretty_name(char *filename) { return (strcmp(filename, "-") == 0) ? "standard input" : filename; } static void write_header(char *filename) { static unsigned short first_file = 1; static char *last = NULL; if (last != filename) { fprintf(stdout, "%s==> %s <==\n", (first_file ? "" : "\n"), pretty_name(filename)); fflush(stdout); /* Make sure the header is printed before the content */ } first_file = 0; last = filename; } static off_t lines_to_offset_from_end(struct file_struct *f, unsigned long n_lines) { off_t offset = f->size; char *buf = emalloc(f->blksize); n_lines++; /* We also count the last \n */ while (offset > 0 && n_lines > 0) { int i; ssize_t rc, block_size = f->blksize; /* Size of the current block we're reading */ if (offset < block_size) block_size = offset; /* Start of current block */ offset -= block_size; if (lseek(f->fd, offset, SEEK_SET) == (off_t) -1) { fprintf(stderr, "Error: Could not seek in file '%s' (%s)\n", f->name, strerror(errno)); free(buf); return -1; } rc = read(f->fd, buf, block_size); if (unlikely(rc < 0)) { fprintf(stderr, "Error: Could not read from file '%s' (%s)\n", f->name, strerror(errno)); free(buf); return -1; } for (i = block_size - 1; i > 0; i--) { if (buf[i] == '\n') { if (--n_lines == 0) { free(buf); return offset += i + 1; /* We don't want the first \n */ } } } } free(buf); return offset; } static off_t lines_to_offset_from_begin(struct file_struct *f, unsigned long n_lines) { char *buf; off_t offset = 0; /* tail everything for 'inotail -n +0' */ if (n_lines == 0) return 0; n_lines--; buf = emalloc(f->blksize); while (offset <= f->size && n_lines > 0) { int i; ssize_t rc, block_size = f->blksize; if (lseek(f->fd, offset, SEEK_SET) == (off_t) -1) { fprintf(stderr, "Error: Could not seek in file '%s' (%s)\n", f->name, strerror(errno)); free(buf); return -1; } rc = read(f->fd, buf, block_size); if (unlikely(rc < 0)) { fprintf(stderr, "Error: Could not read from file '%s' (%s)\n", f->name, strerror(errno)); free(buf); return -1; } else if (rc < block_size) block_size = rc; for (i = 0; i < block_size; i++) { if (buf[i] == '\n') { if (--n_lines == 0) { free(buf); return offset + i + 1; } } } offset += block_size; } free(buf); return offset; } static off_t lines_to_offset(struct file_struct *f, unsigned long n_lines) { if (from_begin) return lines_to_offset_from_begin(f, n_lines); else return lines_to_offset_from_end(f, n_lines); } static off_t bytes_to_offset(struct file_struct *f, unsigned long n_bytes) { off_t offset = 0; /* tail everything for 'inotail -c +0' */ if (from_begin) { if (n_bytes > 0) offset = (off_t) n_bytes - 1; } else if ((off_t) n_bytes < f->size) offset = f->size - (off_t) n_bytes; return offset; } static ssize_t tail_pipe(struct file_struct *f) { ssize_t rc; char *buf = emalloc(f->blksize); if (verbose) write_header(f->name); /* We will just tail everything here */ while ((rc = read(f->fd, buf, f->blksize)) > 0) { if (write(STDOUT_FILENO, buf, (size_t) rc) <= 0) { /* e.g. when writing to a pipe which gets closed */ fprintf(stderr, "Error: Could not write to stdout (%s)\n", strerror(errno)); rc = -1; break; } } free(buf); return rc; } static int tail_file(struct file_struct *f, unsigned long n_units, char mode, char forever) { ssize_t bytes_read = 0; off_t offset = 0; char *buf; struct stat finfo; if (strcmp(f->name, "-") == 0) f->fd = STDIN_FILENO; else { f->fd = open(f->name, O_RDONLY); if (unlikely(f->fd < 0)) { fprintf(stderr, "Error: Could not open file '%s' (%s)\n", f->name, strerror(errno)); ignore_file(f); return -1; } } if (fstat(f->fd, &finfo) < 0) { fprintf(stderr, "Error: Could not stat file '%s' (%s)\n", f->name, strerror(errno)); ignore_file(f); return -1; } if (!IS_TAILABLE(finfo.st_mode)) { fprintf(stderr, "Error: '%s' of unsupported file type (%s)\n", f->name, strerror(errno)); ignore_file(f); return -1; } /* Cannot seek on these */ if (IS_PIPELIKE(finfo.st_mode) || f->fd == STDIN_FILENO) return tail_pipe(f); f->size = finfo.st_size; f->blksize = finfo.st_blksize; /* TODO: Can this value be 0? */ if (mode == M_LINES) offset = lines_to_offset(f, n_units); else offset = bytes_to_offset(f, n_units); /* We only get negative offsets on errors */ if (unlikely(offset < 0)) { ignore_file(f); return -1; } if (verbose) write_header(f->name); if (lseek(f->fd, offset, SEEK_SET) == (off_t) -1) { fprintf(stderr, "Error: Could not seek in file '%s' (%s)\n", f->name, strerror(errno)); return -1; } buf = emalloc(f->blksize); while ((bytes_read = read(f->fd, buf, f->blksize)) > 0) write(STDOUT_FILENO, buf, (size_t) bytes_read); if (!forever) { if (close(f->fd) < 0) { fprintf(stderr, "Error: Could not close file '%s' (%s)\n", f->name, strerror(errno)); free(buf); return -1; } } /* Let the fd open otherwise, we'll need it */ free(buf); return 0; } static int handle_inotify_event(struct inotify_event *inev, struct file_struct *f) { int ret = 0; if (inev->mask & IN_MODIFY) { char *fbuf; ssize_t rc; struct stat finfo; if (verbose) write_header(f->name); /* Seek to old file size */ if (lseek(f->fd, f->size, SEEK_SET) == (off_t) -1) { fprintf(stderr, "Error: Could not seek in file '%s' (%s)\n", f->name, strerror(errno)); ret = -1; goto ignore; } fbuf = emalloc(f->blksize); while ((rc = read(f->fd, fbuf, f->blksize)) != 0) write(STDOUT_FILENO, fbuf, (size_t) rc); if (fstat(f->fd, &finfo) < 0) { fprintf(stderr, "Error: Could not stat file '%s' (%s)\n", f->name, strerror(errno)); ret = -1; free(fbuf); goto ignore; } f->size = finfo.st_size; free(fbuf); return ret; } else if (inev->mask & IN_DELETE_SELF) { fprintf(stderr, "File '%s' deleted.\n", f->name); } else if (inev->mask & IN_MOVE_SELF) { fprintf(stderr, "File '%s' moved.\n", f->name); return 0; } else if (inev->mask & IN_UNMOUNT) { fprintf(stderr, "Device containing file '%s' unmounted.\n", f->name); } ignore: ignore_file(f); return ret; } static int watch_files(struct file_struct *files, int n_files) { int ifd, i; char buf[n_files * INOTIFY_BUFLEN]; ifd = inotify_init(); if (errno == ENOSYS) { fprintf(stderr, "Error: inotify is not supported by the kernel you're currently running.\n"); exit(EXIT_FAILURE); } else if (unlikely(ifd < 0)) { fprintf(stderr, "Error: Could not initialize inotify (%s)\n", strerror(errno)); exit(EXIT_FAILURE); } for (i = 0; i < n_files; i++) { if (!files[i].ignore) { files[i].i_watch = inotify_add_watch(ifd, files[i].name, IN_MODIFY|IN_DELETE_SELF|IN_MOVE_SELF|IN_UNMOUNT); if (files[i].i_watch < 0) { fprintf(stderr, "Error: Could not create inotify watch on file '%s' (%s)\n", files[i].name, strerror(errno)); ignore_file(&files[i]); } } } while (n_ignored < n_files) { ssize_t len; int ev_idx = 0; len = read(ifd, buf, (n_files * INOTIFY_BUFLEN)); if (unlikely(len < 0)) { /* Some signal, likely ^Z/fg's STOP and CONT interrupted the inotify read, retry */ if (errno == EINTR || errno == EAGAIN) continue; else { fprintf(stderr, "Error: Could not read inotify events (%s)\n", strerror(errno)); exit(EXIT_FAILURE); } } while (ev_idx < len) { struct inotify_event *inev; struct file_struct *f = NULL; inev = (struct inotify_event *) &buf[ev_idx]; /* Which file has produced the event? */ for (i = 0; i < n_files; i++) { if (!files[i].ignore && files[i].fd >= 0 && files[i].i_watch == inev->wd) { f = &files[i]; break; } } if (unlikely(!f)) break; if (handle_inotify_event(inev, f) < 0) break; ev_idx += sizeof(struct inotify_event) + inev->len; } } close(ifd); return -1; } int main(int argc, char **argv) { int i, c, ret = 0; int n_files; unsigned long n_units = DEFAULT_N_LINES; char forever = 0, mode = M_LINES; char **filenames; struct file_struct *files = NULL; while ((c = getopt_long(argc, argv, "c:n:fvVh", long_opts, NULL)) != -1) { switch (c) { case 'c': mode = M_BYTES; /* fall through */ case 'n': if (*optarg == '+') { from_begin = 1; optarg++; } else if (*optarg == '-') optarg++; if (!is_digit(*optarg)) { fprintf(stderr, "Error: Invalid number of units: %s\n", optarg); exit(EXIT_FAILURE); } n_units = strtoul(optarg, NULL, 0); break; case 'f': forever = 1; break; case 'v': verbose = 1; break; case 'V': fprintf(stdout, "%s %s\n", PROGRAM_NAME, VERSION); exit(EXIT_SUCCESS); case 'h': usage(EXIT_SUCCESS); default: usage(EXIT_FAILURE); } } /* Do we have some files to read from? */ if (optind < argc) { n_files = argc - optind; filenames = argv + optind; } else { /* It must be stdin then */ static char *dummy_stdin = "-"; n_files = 1; filenames = &dummy_stdin; /* POSIX says that -f is ignored if no file operand is specified and standard input is a pipe. */ if (forever) { struct stat finfo; int rc = fstat(STDIN_FILENO, &finfo); if (unlikely(rc == -1)) { fprintf(stderr, "Error: Could not stat stdin (%s)\n", strerror(errno)); exit(EXIT_FAILURE); } if (rc == 0 && IS_PIPELIKE(finfo.st_mode)) forever = 0; } } files = emalloc(n_files * sizeof(struct file_struct)); for (i = 0; i < n_files; i++) { files[i].name = filenames[i]; setup_file(&files[i]); ret = tail_file(&files[i], n_units, mode, forever); if (ret < 0) ignore_file(&files[i]); } if (forever) ret = watch_files(files, n_files); free(files); return ret; } inotail-0.5/inotail.h000066400000000000000000000023411067023336200146270ustar00rootroot00000000000000/* * Copyright (C) 2005-2007, Tobias Klauser * * Licensed under the terms of the GNU General Public License; version 2 or later. */ #ifndef _INOTAIL_H #define _INOTAIL_H #include /* Number of items to tail. */ #define DEFAULT_N_LINES 10 /* tail modes */ enum { M_LINES, M_BYTES }; /* Every tailed file is represented as a file_struct */ struct file_struct { char *name; /* Name of file (or '-' for stdin) */ int fd; /* File descriptor (or -1 if file is not open */ off_t size; /* File size */ blksize_t blksize; /* Blocksize for filesystem I/O */ unsigned ignore; /* Whether to ignore the file in further processing */ int i_watch; /* Inotify watch associated with file_struct */ }; #define IS_PIPELIKE(mode) \ (S_ISFIFO(mode) || S_ISSOCK(mode)) /* inotail works on these file types */ #define IS_TAILABLE(mode) \ (S_ISREG(mode) || IS_PIPELIKE(mode) || S_ISCHR(mode)) #define is_digit(c) ((c) >= '0' && (c) <= '9') #ifdef DEBUG # define dprintf(fmt, args...) fprintf(stderr, fmt, ##args) #else # define dprintf(fmt, args...) #endif /* DEBUG */ #ifdef __GNUC__ # define unlikely(x) __builtin_expect(!!(x), 0) #else # define unlikely(x) (x) #endif /* __GNUC__ */ #endif /* _INOTAIL_H */ inotail-0.5/inotify-syscalls.h000066400000000000000000000062051067023336200165070ustar00rootroot00000000000000/* * Inotify syscall numbers * Taken from the Linux kernel source tree * * Licensed under the terms of the GNU General Public License Version 2. * * Copyright (c) 2006-2007 Tobias Klauser */ #ifndef _LINUX_INOTIFY_SYSCALLS_H #define _LINUX_INOTIFY_SYSCALLS_H #include /* glibc already defines them for some architectures */ #ifndef __NR_inotify_init #if defined(__i386__) # define __NR_inotify_init 291 # define __NR_inotify_add_watch 292 # define __NR_inotify_rm_watch 293 #elif defined(__x86_64__) # define __NR_inotify_init 253 # define __NR_inotify_add_watch 254 # define __NR_inotify_rm_watch 255 #elif defined(__powerpc__) || defined(__powerpc64__) # define __NR_inotify_init 275 # define __NR_inotify_add_watch 276 # define __NR_inotify_rm_watch 277 #elif defined (__ia64__) # define __NR_inotify_init 1277 # define __NR_inotify_add_watch 1278 # define __NR_inotify_rm_watch 1279 #elif defined (__s390__) # define __NR_inotify_init 284 # define __NR_inotify_add_watch 285 # define __NR_inotify_rm_watch 286 #elif defined (__alpha__) # define __NR_inotify_init 444 # define __NR_inotify_add_watch 445 # define __NR_inotify_rm_watch 446 #elif defined (__sparc__) || defined (__sparc64__) # define __NR_inotify_init 151 # define __NR_inotify_add_watch 152 # define __NR_inotify_rm_watch 156 #elif defined (__arm__) # define __NR_inotify_init (__NR_SYSCALL_BASE + 316) # define __NR_inotify_add_watch (__NR_SYSCALL_BASE + 317) # define __NR_inotify_rm_watch (__NR_SYSCALL_BASE + 318) #elif defined (__sh__) # define __NR_inotify_init 290 # define __NR_inotify_add_watch 291 # define __NR_inotify_rm_watch 292 #elif defined (__m32r__) # define __NR_inotify_init 290 # define __NR_inotify_add_watch 291 # define __NR_inotify_rm_watch 292 #elif defined (__hppa__) # define __NR_inotify_init 269 # define __NR_inotify_add_watch 270 # define __NR_inotify_rm_watch 271 #elif defined (__mips__) # include # if _MIPS_SIM == _MIPS_SIM_ABI32 # define __NR_Linux 4000 # define __NR_inotify_init (__NR_Linux + 284) # define __NR_inotify_add_watch (__NR_Linux + 285) # define __NR_inotify_rm_watch (__NR_Linux + 286) # elif _MIPS_SIM == _MIPS_SIM_ABI64 # define __NR_Linux 5000 # define __NR_inotify_init (__NR_Linux + 243) # define __NR_inotify_add_watch (__NR_Linux + 244) # define __NR_inotify_rm_watch (__NR_Linux + 245) # elif _MIPS_SIM == _MIPS_SIM_NABI32 # define __NR_Linux 6000 # define __NR_inotify_init (__NR_Linux + 247) # define __NR_inotify_add_watch (__NR_Linux + 248) # define __NR_inotify_rm_watch (__NR_Linux + 249) # endif #elif defined (__m68k__) # define __NR_inotify_init 284 # define __NR_inotify_add_watch 285 # define __NR_inotify_rm_watch 286 #else # error "inotify not supported on this architecture!" #endif #endif /* __NR_inotify_init */ static inline int inotify_init(void) { return syscall(__NR_inotify_init); } static inline int inotify_add_watch(int fd, const char *name, __u32 mask) { return syscall(__NR_inotify_add_watch, fd, name, mask); } static inline int inotify_rm_watch(int fd, __u32 wd) { return syscall(__NR_inotify_rm_watch, fd, wd); } #endif /* _LINUX_INOTIFY_SYSCALLS_H */ inotail-0.5/inotify.h000066400000000000000000000053571067023336200146630ustar00rootroot00000000000000/* * Inode based directory notification for Linux * Taken from the Linux kernel source tree * * Licensed under the terms of the GNU General Public License Version 2. * * Copyright (C) 2005 John McCutchan */ #ifndef _LINUX_INOTIFY_H #define _LINUX_INOTIFY_H #include /* * struct inotify_event - structure read from the inotify device for each event * * When you are watching a directory, you will receive the filename for events * such as IN_CREATE, IN_DELETE, IN_OPEN, IN_CLOSE, ..., relative to the wd. */ struct inotify_event { __s32 wd; /* watch descriptor */ __u32 mask; /* watch mask */ __u32 cookie; /* cookie to synchronize two events */ __u32 len; /* length (including nulls) of name */ char name[0]; /* stub for possible name */ }; /* the following are legal, implemented events that user-space can watch for */ #define IN_ACCESS 0x00000001 /* File was accessed */ #define IN_MODIFY 0x00000002 /* File was modified */ #define IN_ATTRIB 0x00000004 /* Metadata changed */ #define IN_CLOSE_WRITE 0x00000008 /* Writtable file was closed */ #define IN_CLOSE_NOWRITE 0x00000010 /* Unwrittable file closed */ #define IN_OPEN 0x00000020 /* File was opened */ #define IN_MOVED_FROM 0x00000040 /* File was moved from X */ #define IN_MOVED_TO 0x00000080 /* File was moved to Y */ #define IN_CREATE 0x00000100 /* Subfile was created */ #define IN_DELETE 0x00000200 /* Subfile was deleted */ #define IN_DELETE_SELF 0x00000400 /* Self was deleted */ #define IN_MOVE_SELF 0x00000800 /* Self was moved */ /* the following are legal events. they are sent as needed to any watch */ #define IN_UNMOUNT 0x00002000 /* Backing fs was unmounted */ #define IN_Q_OVERFLOW 0x00004000 /* Event queued overflowed */ #define IN_IGNORED 0x00008000 /* File was ignored */ /* helper events */ #define IN_CLOSE (IN_CLOSE_WRITE | IN_CLOSE_NOWRITE) /* close */ #define IN_MOVE (IN_MOVED_FROM | IN_MOVED_TO) /* moves */ /* special flags */ #define IN_ONLYDIR 0x01000000 /* only watch the path if it is a directory */ #define IN_DONT_FOLLOW 0x02000000 /* don't follow a sym link */ #define IN_MASK_ADD 0x20000000 /* add to the mask of an already existing watch */ #define IN_ISDIR 0x40000000 /* event occurred against dir */ #define IN_ONESHOT 0x80000000 /* only send event once */ /* * All of the events - we build the list by hand so that we can add flags in * the future and not break backward compatibility. Apps will get only the * events that they originally wanted. Be sure to add new events here! */ #define IN_ALL_EVENTS (IN_ACCESS | IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | \ IN_CLOSE_NOWRITE | IN_OPEN | IN_MOVED_FROM | \ IN_MOVED_TO | IN_DELETE | IN_CREATE | IN_DELETE_SELF | \ IN_MOVE_SELF) #endif /* _LINUX_INOTIFY_H */