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 * Deviations from posix: -f waits for pipe/fifo on stdin (nonblock?).
9 USE_TAIL(NEWTOY(tail, "?fc-n-[-cn]", TOYFLAG_USR|TOYFLAG_BIN))
15 usage: tail [-n|c NUMBER] [-f] [FILE...]
17 Copy last lines from files to stdout. If no files listed, copy from
18 stdin. Filename "-" is a synonym for stdin.
20 -n output the last NUMBER lines (default 10), +X counts from start.
21 -c output the last NUMBER bytes, +NUMBER counts from start
22 -f follow FILE(s), waiting for more data to be appended
25 bool "tail seek support"
29 This version uses lseek, which is faster on large files.
34 #include <sys/inotify.h>
40 int file_no, ffd, *files;
44 struct line_list *next, *prev;
49 static struct line_list *get_chunk(int fd, int len)
51 struct line_list *line = xmalloc(sizeof(struct line_list)+len);
53 memset(line, 0, sizeof(struct line_list));
54 line->data = ((char *)line) + sizeof(struct line_list);
55 line->len = readall(fd, line->data, len);
65 static void dump_chunk(void *ptr)
67 struct line_list *list = ptr;
69 xwrite(1, list->data, list->len);
73 // Reading through very large files is slow. Using lseek can speed things
74 // up a lot, but isn't applicable to all input (cat | tail).
75 // Note: bytes and lines are negative here.
76 static int try_lseek(int fd, long bytes, long lines)
78 struct line_list *list = 0, *temp;
79 int flag = 0, chunk = sizeof(toybuf);
80 off_t pos = lseek(fd, 0, SEEK_END);
82 // If lseek() doesn't work on this stream, return now.
85 // Seek to the right spot, output data from there.
87 if (lseek(fd, bytes, SEEK_END)<0) lseek(fd, 0, SEEK_SET);
92 // Read from end to find enough lines, then output them.
95 while (lines && pos) {
98 // Read in next chunk from end of file
99 if (chunk>pos) chunk = pos;
101 if (pos != lseek(fd, pos, SEEK_SET)) {
102 perror_msg("seek failed");
105 if (!(temp = get_chunk(fd, chunk))) break;
109 // Count newlines in this chunk.
112 // If the last line ends with a newline, that one doesn't count.
115 // Start outputting data right after newline
116 else if (list->data[offset] == '\n' && !++lines) {
118 list->data += offset;
126 // Output stored data
127 llist_traverse(list, dump_chunk);
130 lseek(fd, bytes, SEEK_SET);
134 // Called for each file listed on command line, and/or stdin
135 static void do_tail(int fd, char *name)
137 long bytes = TT.bytes, lines = TT.lines;
140 if (toys.optflags & FLAG_f) {
141 int f = TT.file_no*2;
144 if (!fd) sprintf(s = toybuf, "/proc/self/fd/%d", fd);
146 if (0 > (TT.files[f] = inotify_add_watch(TT.ffd, s, IN_MODIFY)))
147 perror_msg("bad -f on '%s'", name);
150 if (TT.file_no++) xputc('\n');
151 if (toys.optc > 1) 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++));
235 // 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|WARN_ONLY|(O_CLOEXEC*!(toys.optflags&FLAG_f)),
248 if ((toys.optflags & FLAG_f) && TT.file_no) {
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);