dmesg.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. *
  4. * dmesg - display/control kernel ring buffer.
  5. *
  6. * Copyright 2006 Rob Landley <rob@landley.net>
  7. * Copyright 2006 Bernhard Reutner-Fischer <rep.nop@aon.at>
  8. *
  9. * Licensed under GPLv2, see file LICENSE in this source tree.
  10. */
  11. #include <sys/klog.h>
  12. #include "libbb.h"
  13. int dmesg_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  14. int dmesg_main(int argc UNUSED_PARAM, char **argv)
  15. {
  16. int len, level;
  17. char *buf;
  18. unsigned opts;
  19. enum {
  20. OPT_c = 1 << 0,
  21. OPT_s = 1 << 1,
  22. OPT_n = 1 << 2
  23. };
  24. opt_complementary = "s+:n+"; /* numeric */
  25. opts = getopt32(argv, "cs:n:", &len, &level);
  26. if (opts & OPT_n) {
  27. if (klogctl(8, NULL, (long) level))
  28. bb_perror_msg_and_die("klogctl");
  29. return EXIT_SUCCESS;
  30. }
  31. if (!(opts & OPT_s))
  32. len = klogctl(10, NULL, 0); /* read ring buffer size */
  33. if (len < 16*1024)
  34. len = 16*1024;
  35. if (len > 16*1024*1024)
  36. len = 16*1024*1024;
  37. buf = xmalloc(len);
  38. len = klogctl(3 + (opts & OPT_c), buf, len); /* read ring buffer */
  39. if (len < 0)
  40. bb_perror_msg_and_die("klogctl");
  41. if (len == 0)
  42. return EXIT_SUCCESS;
  43. if (ENABLE_FEATURE_DMESG_PRETTY) {
  44. int last = '\n';
  45. int in = 0;
  46. /* Skip <#> at the start of lines */
  47. while (1) {
  48. if (last == '\n' && buf[in] == '<') {
  49. in += 3;
  50. if (in >= len)
  51. break;
  52. }
  53. last = buf[in];
  54. putchar(last);
  55. in++;
  56. if (in >= len)
  57. break;
  58. }
  59. /* Make sure we end with a newline */
  60. if (last != '\n')
  61. bb_putchar('\n');
  62. } else {
  63. full_write(STDOUT_FILENO, buf, len);
  64. if (buf[len-1] != '\n')
  65. bb_putchar('\n');
  66. }
  67. if (ENABLE_FEATURE_CLEAN_UP) free(buf);
  68. return EXIT_SUCCESS;
  69. }