ts.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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 ""
  14. #include "libbb.h"
  15. #include "common_bufsiz.h"
  16. int ts_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  17. int ts_main(int argc UNUSED_PARAM, char **argv)
  18. {
  19. struct timeval base;
  20. unsigned opt;
  21. char *frac;
  22. char *fmt_dt2str;
  23. char *line;
  24. opt = getopt32(argv, "^" "is" "\0" "?1" /*max one arg*/);
  25. if (opt) {
  26. putenv((char*)"TZ=UTC0");
  27. tzset();
  28. }
  29. /*argc -= optind;*/
  30. argv += optind;
  31. fmt_dt2str = argv[0] ? argv[0]
  32. : (char*)(opt ? "%b %d %H:%M:%S"+6 : "%b %d %H:%M:%S");
  33. frac = is_suffixed_with(fmt_dt2str, "%.S");
  34. if (!frac)
  35. frac = is_suffixed_with(fmt_dt2str, "%.s");
  36. if (frac) {
  37. frac++;
  38. frac[0] = frac[1];
  39. frac[1] = '\0';
  40. }
  41. #define date_buf bb_common_bufsiz1
  42. setup_common_bufsiz();
  43. xgettimeofday(&base);
  44. while ((line = xmalloc_fgets(stdin)) != NULL) {
  45. struct timeval ts;
  46. struct tm tm_time;
  47. xgettimeofday(&ts);
  48. if (opt) {
  49. /* -i and/or -s */
  50. struct timeval ts1 = ts1;
  51. if (opt & 1) /* -i */
  52. ts1 = ts;
  53. //printf("%d %d\n", ts.tv_sec, base.tv_sec);
  54. ts.tv_sec -= base.tv_sec;
  55. //printf("%d %d\n", ts.tv_sec, base.tv_sec);
  56. ts.tv_usec -= base.tv_usec;
  57. if ((int32_t)(ts.tv_usec) < 0) {
  58. ts.tv_sec--;
  59. ts.tv_usec += 1000*1000;
  60. }
  61. if (opt & 1) /* -i */
  62. base = ts1;
  63. }
  64. localtime_r(&ts.tv_sec, &tm_time);
  65. strftime(date_buf, COMMON_BUFSIZE, fmt_dt2str, &tm_time);
  66. if (!frac) {
  67. printf("%s %s", date_buf, line);
  68. } else {
  69. printf("%s.%06u %s", date_buf, (unsigned)ts.tv_usec, line);
  70. }
  71. free(line);
  72. }
  73. return EXIT_SUCCESS;
  74. }