ts.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Copyright (C) 2019 Denys Vlasenko <vda.linux@googlemail.com>
  4. * Licensed under GPLv2, see file LICENSE in this source tree.
  5. */
  6. //config:config TS
  7. //config: bool "ts (450 bytes)"
  8. //config: default y
  9. //applet:IF_TS(APPLET(ts, BB_DIR_USR_BIN, BB_SUID_DROP))
  10. //kbuild:lib-$(CONFIG_TS) += ts.o
  11. //usage:#define ts_trivial_usage
  12. //usage: "[-is] [STRFTIME]"
  13. //usage:#define ts_full_usage "\n\n"
  14. //usage: "Pipe stdin to stdout, add timestamp to each line\n"
  15. //usage: "\n -s Time since start"
  16. //usage: "\n -i Time since previous line"
  17. #include "libbb.h"
  18. #include "common_bufsiz.h"
  19. int ts_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  20. int ts_main(int argc UNUSED_PARAM, char **argv)
  21. {
  22. struct timeval base;
  23. unsigned opt;
  24. char *frac;
  25. char *fmt_dt2str;
  26. char *line;
  27. opt = getopt32(argv, "^" "is" "\0" "?1" /*max one arg*/);
  28. if (opt) {
  29. putenv((char*)"TZ=UTC0");
  30. tzset();
  31. }
  32. /*argc -= optind;*/
  33. argv += optind;
  34. fmt_dt2str = argv[0] ? argv[0]
  35. : (char*)(opt ? "%b %d %H:%M:%S"+6 : "%b %d %H:%M:%S");
  36. frac = is_suffixed_with(fmt_dt2str, "%.S");
  37. if (!frac)
  38. frac = is_suffixed_with(fmt_dt2str, "%.s");
  39. if (frac) {
  40. frac++;
  41. frac[0] = frac[1];
  42. frac[1] = '\0';
  43. }
  44. #define date_buf bb_common_bufsiz1
  45. setup_common_bufsiz();
  46. xgettimeofday(&base);
  47. while ((line = xmalloc_fgets(stdin)) != NULL) {
  48. struct timeval ts;
  49. struct tm tm_time;
  50. xgettimeofday(&ts);
  51. if (opt) {
  52. /* -i and/or -s */
  53. struct timeval ts1 = ts1;
  54. if (opt & 1) /* -i */
  55. ts1 = ts;
  56. //printf("%d %d\n", ts.tv_sec, base.tv_sec);
  57. ts.tv_sec -= base.tv_sec;
  58. //printf("%d %d\n", ts.tv_sec, base.tv_sec);
  59. ts.tv_usec -= base.tv_usec;
  60. if ((int32_t)(ts.tv_usec) < 0) {
  61. ts.tv_sec--;
  62. ts.tv_usec += 1000*1000;
  63. }
  64. if (opt & 1) /* -i */
  65. base = ts1;
  66. }
  67. localtime_r(&ts.tv_sec, &tm_time);
  68. strftime(date_buf, COMMON_BUFSIZE, fmt_dt2str, &tm_time);
  69. if (!frac) {
  70. printf("%s %s", date_buf, line);
  71. } else {
  72. printf("%s.%06u %s", date_buf, (unsigned)ts.tv_usec, line);
  73. }
  74. free(line);
  75. }
  76. return EXIT_SUCCESS;
  77. }