1 /* tail.c - copy last lines from input to stdout.
3 * Copyright 2012 Timothy Elliott <tle@holymonkey.com>
5 * See http://opengroup.org/onlinepubs/9699919799/utilities/tail.html
7 USE_TAIL(NEWTOY(tail, "?fc-n-[-cn]", TOYFLAG_USR|TOYFLAG_BIN))
13 usage: tail [-n|c NUMBER] [-f] [FILE...]
15 Copy last lines from files to stdout. If no files listed, copy from
16 stdin. Filename "-" is a synonym for stdin.
18 -n output the last NUMBER lines (default 10), +X counts from start.
19 -c output the last NUMBER bytes, +NUMBER counts from start
20 -f follow FILE(s), waiting for more data to be appended
23 bool "tail seek support"
27 This version uses lseek, which is faster on large files.
32 #include <sys/inotify.h>
38 int file_no, ffd, *files;
42 struct line_list *next, *prev;
47 static struct line_list *get_chunk(int fd, int len)
49 struct line_list *line = xmalloc(sizeof(struct line_list)+len);
51 memset(line, 0, sizeof(struct line_list));
52 line->data = ((char *)line) + sizeof(struct line_list);
53 line->len = readall(fd, line->data, len);
63 static void dump_chunk(void *ptr)
65 struct line_list *list = ptr;
67 xwrite(1, list->data, list->len);
71 // Reading through very large files is slow. Using lseek can speed things
72 // up a lot, but isn't applicable to all input (cat | tail).
73 // Note: bytes and lines are negative here.
74 static int try_lseek(int fd, long bytes, long lines)
76 struct line_list *list = 0, *temp;
77 int flag = 0, chunk = sizeof(toybuf);
78 off_t pos = lseek(fd, 0, SEEK_END);
80 // If lseek() doesn't work on this stream, return now.
83 // Seek to the right spot, output data from there.
85 if (lseek(fd, bytes, SEEK_END)<0) lseek(fd, 0, SEEK_SET);
90 // Read from end to find enough lines, then output them.
93 while (lines && pos) {
96 // Read in next chunk from end of file
97 if (chunk>pos) chunk = pos;
99 if (pos != lseek(fd, pos, SEEK_SET)) {
100 perror_msg("seek failed");
103 if (!(temp = get_chunk(fd, chunk))) break;
107 // Count newlines in this chunk.
110 // If the last line ends with a newline, that one doesn't count.
113 // Start outputting data right after newline
114 else if (list->data[offset] == '\n' && !++lines) {
116 list->data += offset;
124 // Output stored data
125 llist_traverse(list, dump_chunk);
128 lseek(fd, bytes, SEEK_SET);
132 // Called for each file listed on command line, and/or stdin
133 static void do_tail(int fd, char *name)
135 long bytes = TT.bytes, lines = TT.lines;
138 if (toys.optflags & FLAG_f) {
139 int f = TT.file_no*2;
142 if (!fd) sprintf(s = toybuf, "/proc/self/fd/%d", fd);
144 if (0 > (TT.files[f] = inotify_add_watch(TT.ffd, s, IN_MODIFY)))
145 perror_msg("bad -f on '%s'", name);
149 if (TT.file_no++) xputc('\n');
150 xprintf("==> %s <==\n", name);
153 // Are we measuring from the end of the file?
155 if (bytes<0 || lines<0) {
156 struct line_list *list = 0, *new;
158 // The slow codepath is always needed, and can handle all input,
159 // so make lseek support optional.
160 if (CFG_TAIL_SEEK && try_lseek(fd, bytes, lines)) return;
162 // Read data until we run out, keep a trailing buffer
164 // Read next page of data, appending to linked list in order
165 if (!(new = get_chunk(fd, sizeof(toybuf)))) break;
166 dlist_add_nomalloc((void *)&list, (void *)new);
168 // If tracing bytes, add until we have enough, discarding overflow.
172 while (list->len <= bytes) {
174 free(dlist_pop(&list));
181 int len = new->len, count;
182 char *try = new->data;
184 // First character _after_ a newline starts a new line, which
185 // works even if file doesn't end with a newline
186 for (count=0; count<len; count++) {
187 if (linepop) lines++;
188 linepop = try[count] == '\n';
195 if (!--(list->len)) free(dlist_pop(&list));
204 // Output/free the buffer.
205 llist_traverse(list, dump_chunk);
207 // Measuring from the beginning of the file.
211 // Error while reading does not exit. Error writing does.
212 len = read(fd, toybuf, sizeof(toybuf));
214 while (bytes > 1 || lines > 1) {
216 if (toybuf[offset++] == '\n') lines--;
217 if (offset >= len) break;
219 if (offset<len) xwrite(1, toybuf+offset, len-offset);
225 char **args = toys.optargs;
227 if (!(toys.optflags&(FLAG_n|FLAG_c))) {
230 // handle old "-42" style arguments
231 if (arg && *arg == '-' && arg[1]) {
232 TT.lines = atolx(*(args++));
236 // if nothing specified, default -n to -10
240 // Allocate 2 ints per optarg for -f
241 if (toys.optflags&FLAG_f) {
242 if ((TT.ffd = inotify_init()) < 0) perror_exit("inotify_init");
243 TT.files = xmalloc(toys.optc*8);
245 loopfiles_rw(args, O_RDONLY|(O_CLOEXEC*!(toys.optflags&FLAG_f)),
248 if (toys.optflags & FLAG_f) {
249 int len, last_fd = TT.files[(TT.file_no-1)*2], i, fd;
250 struct inotify_event ev;
253 if (sizeof(ev)!=read(TT.ffd, &ev, sizeof(ev))) perror_exit("inotify");
255 for (i = 0; i<TT.file_no && ev.wd!=TT.files[(i*2)+1]; i++);
256 if (i==TT.file_no) continue;
260 while ((len = read(fd, toybuf, sizeof(toybuf)))>0) {
263 xprintf("\n==> %s <==\n", args[i]);
266 xwrite(1, toybuf, len);