tail.c 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. /* tail.c - copy last lines from input to stdout.
  2. *
  3. * Copyright 2012 Timothy Elliott <tle@holymonkey.com>
  4. *
  5. * See http://opengroup.org/onlinepubs/9699919799/utilities/tail.html
  6. *
  7. * Deviations from posix: -f waits for pipe/fifo on stdin (nonblock?).
  8. USE_TAIL(NEWTOY(tail, "?fFs:c(bytes)-n(lines)-[-cn][-fF]", TOYFLAG_USR|TOYFLAG_BIN))
  9. config TAIL
  10. bool "tail"
  11. default y
  12. help
  13. usage: tail [-n|c NUMBER] [-f|F] [-s SECONDS] [FILE...]
  14. Copy last lines from files to stdout. If no files listed, copy from
  15. stdin. Filename "-" is a synonym for stdin.
  16. -n Output the last NUMBER lines (default 10), +X counts from start
  17. -c Output the last NUMBER bytes, +NUMBER counts from start
  18. -f Follow FILE(s) by descriptor, waiting for more data to be appended
  19. -F Follow FILE(s) by filename, waiting for more data, and retrying
  20. -s Used with -F, sleep SECONDS between retries (default 1)
  21. */
  22. #define FOR_tail
  23. #include "toys.h"
  24. GLOBALS(
  25. long n, c;
  26. char *s;
  27. int file_no, last_fd, ss;
  28. struct xnotify *not;
  29. struct {
  30. char *path;
  31. int fd;
  32. dev_t dev;
  33. ino_t ino;
  34. } *F;
  35. )
  36. struct line_list {
  37. struct line_list *next, *prev;
  38. char *data;
  39. int len;
  40. };
  41. static struct line_list *read_chunk(int fd, int len)
  42. {
  43. struct line_list *line = xmalloc(sizeof(struct line_list)+len);
  44. memset(line, 0, sizeof(struct line_list));
  45. line->data = ((char *)line) + sizeof(struct line_list);
  46. line->len = readall(fd, line->data, len);
  47. if (line->len < 1) {
  48. free(line);
  49. return 0;
  50. }
  51. return line;
  52. }
  53. static void write_chunk(void *ptr)
  54. {
  55. struct line_list *list = ptr;
  56. xwrite(1, list->data, list->len);
  57. free(list);
  58. }
  59. // Reading through very large files is slow. Using lseek can speed things
  60. // up a lot, but isn't applicable to all input (cat | tail).
  61. // Note: bytes and lines are negative here.
  62. static int try_lseek(int fd, long bytes, long lines)
  63. {
  64. struct line_list *list = 0, *temp;
  65. int flag = 0, chunk = sizeof(toybuf);
  66. off_t pos = lseek(fd, 0, SEEK_END);
  67. // If lseek() doesn't work on this stream, return now.
  68. if (pos<0) return 0;
  69. // Seek to the right spot, output data from there.
  70. if (bytes) {
  71. if (lseek(fd, bytes, SEEK_END)<0) lseek(fd, 0, SEEK_SET);
  72. xsendfile(fd, 1);
  73. return 1;
  74. }
  75. // Read from end to find enough lines, then output them.
  76. bytes = pos;
  77. while (lines && pos) {
  78. int offset;
  79. // Read in next chunk from end of file
  80. if (chunk>pos) chunk = pos;
  81. pos -= chunk;
  82. if (pos != lseek(fd, pos, SEEK_SET)) {
  83. perror_msg("seek failed");
  84. break;
  85. }
  86. if (!(temp = read_chunk(fd, chunk))) break;
  87. temp->next = list;
  88. list = temp;
  89. // Count newlines in this chunk.
  90. offset = list->len;
  91. while (offset--) {
  92. // If the last line ends with a newline, that one doesn't count.
  93. if (!flag) flag++;
  94. // Start outputting data right after newline
  95. else if (list->data[offset] == '\n' && !++lines) {
  96. offset++;
  97. list->data += offset;
  98. list->len -= offset;
  99. break;
  100. }
  101. }
  102. }
  103. // Output stored data
  104. llist_traverse(list, write_chunk);
  105. // In case of -f
  106. lseek(fd, bytes, SEEK_SET);
  107. return 1;
  108. }
  109. // For -f and -F
  110. static void tail_continue()
  111. {
  112. long long pos;
  113. char *path;
  114. struct stat sb;
  115. int i = 0, fd, len;
  116. for (i = 0; ; i++) {
  117. if (FLAG(f)) fd = xnotify_wait(TT.not, &path);
  118. else {
  119. if (i == TT.file_no) {
  120. i = 0;
  121. msleep(TT.ss);
  122. }
  123. fd = TT.F[i].fd;
  124. path = TT.F[i].path;
  125. if (stat(TT.F[i].path, &sb)) {
  126. if (fd >= 0) {
  127. close(fd);
  128. TT.F[i].fd = -1;
  129. error_msg("file inaccessible: %s\n", TT.F[i].path);
  130. }
  131. continue;
  132. }
  133. if (fd<0 || sb.st_dev!=TT.F[i].dev || sb.st_ino!=TT.F[i].ino) {
  134. if (fd>=0) close(fd);
  135. if (-1 == (TT.F[i].fd = fd = open(path, O_RDONLY))) continue;
  136. error_msg("following new file: %s\n", path);
  137. TT.F[i].dev = sb.st_dev;
  138. TT.F[i].ino = sb.st_ino;
  139. } else if (sb.st_size <= (pos = lseek(fd, 0, SEEK_CUR))) {
  140. if (pos == sb.st_size) continue;
  141. error_msg("file truncated: %s\n", path);
  142. lseek(fd, 0, SEEK_SET);
  143. }
  144. }
  145. while ((len = read(fd, toybuf, sizeof(toybuf)))>0) {
  146. if (TT.file_no>1 && TT.last_fd != fd) {
  147. TT.last_fd = fd;
  148. xprintf("\n==> %s <==\n", path);
  149. }
  150. xwrite(1, toybuf, len);
  151. }
  152. }
  153. }
  154. // Called for each file listed on command line, and/or stdin
  155. static void do_tail(int fd, char *name)
  156. {
  157. long bytes = TT.c, lines = TT.n;
  158. int linepop = 1;
  159. if (FLAG(F)) {
  160. if (!fd) perror_exit("no -F with '-'");
  161. } else if (fd == -1) return;
  162. if (FLAG(f) || FLAG(F)) {
  163. char *s = name;
  164. struct stat sb;
  165. if (!fd) sprintf(s = toybuf, "/proc/self/fd/%d", fd);
  166. if (FLAG(f)) xnotify_add(TT.not, fd, s);
  167. if (FLAG(F)) {
  168. if (fd != -1) {
  169. if (fstat(fd, &sb)) perror_exit("%s", name);
  170. TT.F[TT.file_no].dev = sb.st_dev;
  171. TT.F[TT.file_no].ino = sb.st_ino;
  172. }
  173. TT.F[TT.file_no].fd = fd;
  174. TT.F[TT.file_no].path = s;
  175. }
  176. }
  177. if (TT.file_no++) xputc('\n');
  178. TT.last_fd = fd;
  179. if (toys.optc > 1) xprintf("==> %s <==\n", name);
  180. // Are we measuring from the end of the file?
  181. if (bytes<0 || lines<0) {
  182. struct line_list *list = 0, *new;
  183. // The slow codepath is always needed, and can handle all input,
  184. // so make lseek support optional.
  185. if (try_lseek(fd, bytes, lines)) return;
  186. // Read data until we run out, keep a trailing buffer
  187. for (;;) {
  188. // Read next page of data, appending to linked list in order
  189. if (!(new = read_chunk(fd, sizeof(toybuf)))) break;
  190. dlist_add_nomalloc((void *)&list, (void *)new);
  191. // If tracing bytes, add until we have enough, discarding overflow.
  192. if (TT.c) {
  193. bytes += new->len;
  194. if (bytes > 0) {
  195. while (list->len <= bytes) {
  196. bytes -= list->len;
  197. free(dlist_pop(&list));
  198. }
  199. list->data += bytes;
  200. list->len -= bytes;
  201. bytes = 0;
  202. }
  203. } else {
  204. int len = new->len, count;
  205. char *try = new->data;
  206. // First character _after_ a newline starts a new line, which
  207. // works even if file doesn't end with a newline
  208. for (count=0; count<len; count++) {
  209. if (linepop) lines++;
  210. linepop = try[count] == '\n';
  211. if (lines > 0) {
  212. char c;
  213. do {
  214. c = *list->data;
  215. if (!--(list->len)) free(dlist_pop(&list));
  216. else list->data++;
  217. } while (c != '\n');
  218. lines--;
  219. }
  220. }
  221. }
  222. }
  223. // Output/free the buffer.
  224. llist_traverse(list, write_chunk);
  225. // Measuring from the beginning of the file.
  226. } else for (;;) {
  227. int len, offset = 0;
  228. // Error while reading does not exit. Error writing does.
  229. len = read(fd, toybuf, sizeof(toybuf));
  230. if (len<1) break;
  231. while (bytes > 1 || lines > 1) {
  232. bytes--;
  233. if (toybuf[offset++] == '\n') lines--;
  234. if (offset >= len) break;
  235. }
  236. if (offset<len) xwrite(1, toybuf+offset, len-offset);
  237. }
  238. }
  239. void tail_main(void)
  240. {
  241. char **args = toys.optargs;
  242. if (!FLAG(n) && !FLAG(c)) {
  243. char *arg = *args;
  244. // handle old "-42" style arguments, else default to last 10 lines
  245. if (arg && *arg == '-' && arg[1]) {
  246. TT.n = atolx(*(args++));
  247. toys.optc--;
  248. } else TT.n = -10;
  249. }
  250. if (FLAG(F)) TT.F = xzalloc(toys.optc*sizeof(*TT.F));
  251. else if (FLAG(f)) TT.not = xnotify_init(toys.optc);
  252. TT.ss = TT.s ? xparsemillitime(TT.s) : 1000;
  253. loopfiles_rw(args,
  254. O_RDONLY|WARN_ONLY|LOOPFILES_ANYWAY|(O_CLOEXEC*!(FLAG(f) || FLAG(F))),
  255. 0, do_tail);
  256. // Wait for more data when following files
  257. if (TT.file_no && (FLAG(F) || FLAG(f))) tail_continue();
  258. }