dmesg.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. //usage:#define dmesg_trivial_usage
  12. //usage: "[-c] [-n LEVEL] [-s SIZE]"
  13. //usage:#define dmesg_full_usage "\n\n"
  14. //usage: "Print or control the kernel ring buffer\n"
  15. //usage: "\n -c Clear ring buffer after printing"
  16. //usage: "\n -n LEVEL Set console logging level"
  17. //usage: "\n -s SIZE Buffer size"
  18. //usage: "\n -r Print raw message buffer"
  19. #include <sys/klog.h>
  20. #include "libbb.h"
  21. int dmesg_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  22. int dmesg_main(int argc UNUSED_PARAM, char **argv)
  23. {
  24. int len, level;
  25. char *buf;
  26. unsigned opts;
  27. enum {
  28. OPT_c = 1 << 0,
  29. OPT_s = 1 << 1,
  30. OPT_n = 1 << 2,
  31. OPT_r = 1 << 3
  32. };
  33. opt_complementary = "s+:n+"; /* numeric */
  34. opts = getopt32(argv, "cs:n:r", &len, &level);
  35. if (opts & OPT_n) {
  36. if (klogctl(8, NULL, (long) level))
  37. bb_perror_msg_and_die("klogctl");
  38. return EXIT_SUCCESS;
  39. }
  40. if (!(opts & OPT_s))
  41. len = klogctl(10, NULL, 0); /* read ring buffer size */
  42. if (len < 16*1024)
  43. len = 16*1024;
  44. if (len > 16*1024*1024)
  45. len = 16*1024*1024;
  46. buf = xmalloc(len);
  47. len = klogctl(3 + (opts & OPT_c), buf, len); /* read ring buffer */
  48. if (len < 0)
  49. bb_perror_msg_and_die("klogctl");
  50. if (len == 0)
  51. return EXIT_SUCCESS;
  52. if (ENABLE_FEATURE_DMESG_PRETTY && !(opts & OPT_r)) {
  53. int last = '\n';
  54. int in = 0;
  55. /* Skip <[0-9]+> at the start of lines */
  56. while (1) {
  57. if (last == '\n' && buf[in] == '<') {
  58. while (buf[in++] != '>' && in < len)
  59. ;
  60. } else {
  61. last = buf[in++];
  62. putchar(last);
  63. }
  64. if (in >= len)
  65. break;
  66. }
  67. /* Make sure we end with a newline */
  68. if (last != '\n')
  69. bb_putchar('\n');
  70. } else {
  71. full_write(STDOUT_FILENO, buf, len);
  72. if (buf[len-1] != '\n')
  73. bb_putchar('\n');
  74. }
  75. if (ENABLE_FEATURE_CLEAN_UP) free(buf);
  76. return EXIT_SUCCESS;
  77. }