dmesg.c 1.9 KB

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