dmesg.c 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 tarball for details.
  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. /* Skip <#> at the start of lines, and make sure we end with a newline */
  44. if (ENABLE_FEATURE_DMESG_PRETTY) {
  45. int last = '\n';
  46. int in = 0;
  47. do {
  48. if (last == '\n' && buf[in] == '<')
  49. in += 3;
  50. else {
  51. last = buf[in++];
  52. bb_putchar(last);
  53. }
  54. } while (in < len);
  55. if (last != '\n')
  56. bb_putchar('\n');
  57. } else {
  58. full_write(STDOUT_FILENO, buf, len);
  59. if (buf[len-1] != '\n')
  60. bb_putchar('\n');
  61. }
  62. if (ENABLE_FEATURE_CLEAN_UP) free(buf);
  63. return EXIT_SUCCESS;
  64. }