dmesg.c 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #include "dmesg.h"
  2. #include <stdio.h>
  3. #include <string.h>
  4. /**
  5. * @brief 识别dmesg程序的第一个选项参数
  6. *
  7. * @param arg dmesg命令第一个选项参数
  8. * @return int 有效时返回对应选项码,无效时返回 -1
  9. */
  10. int getoption(char *arg)
  11. {
  12. if (!strcmp(arg, "-h") || !strcmp(arg, "--help"))
  13. return 0;
  14. else if (!strcmp(arg, "-c") || !strcmp(arg, "--read-clear"))
  15. return 4;
  16. else if (!strcmp(arg, "-C") || !strcmp(arg, "--clear"))
  17. return 5;
  18. else if (!strcmp(arg, "-l") || !strcmp(arg, "--level"))
  19. return 8;
  20. return -1;
  21. }
  22. /**
  23. * @brief 识别dmesg程序的第二个选项参数
  24. *
  25. * @param arg dmesg命令第一个选项参数
  26. * @return int 有效时返回设置的日志级别,无效时返回 -1
  27. */
  28. int getlevel(char *arg)
  29. {
  30. if (!strcmp(arg, "EMERG") || !strcmp(arg, "emerg"))
  31. return 0;
  32. else if (!strcmp(arg, "ALERT") || !strcmp(arg, "alert"))
  33. return 1;
  34. else if (!strcmp(arg, "CRIT") || !strcmp(arg, "crit"))
  35. return 2;
  36. else if (!strcmp(arg, "ERR") || !strcmp(arg, "err"))
  37. return 3;
  38. else if (!strcmp(arg, "WARN") || !strcmp(arg, "warn"))
  39. return 4;
  40. else if (!strcmp(arg, "NOTICE") || !strcmp(arg, "notice"))
  41. return 5;
  42. else if (!strcmp(arg, "INFO") || !strcmp(arg, "info"))
  43. return 6;
  44. else if (!strcmp(arg, "DEBUG") || !strcmp(arg, "debug"))
  45. return 7;
  46. else
  47. {
  48. printf("dmesg: unknown level '%s'\n", arg);
  49. }
  50. return -2;
  51. }
  52. /**
  53. * @brief 打印dmesg手册
  54. */
  55. void print_help_msg()
  56. {
  57. const char *help_msg = "Usage:\n"
  58. " dmesg [options]\n\n"
  59. "Display or control the kernel ring buffer.\n\n"
  60. "Options:\n"
  61. " -C, --clear clear the kernel ring buffer\n"
  62. " -c, --read-clear read and clear all messages\n"
  63. " -l, --level <list> restrict output to defined levels\n"
  64. " -h, --help display this help\n\n"
  65. "Supported log levels (priorities):\n"
  66. " emerg - system is unusable\n"
  67. " alert - action must be taken immediately\n"
  68. " crit - critical conditions\n"
  69. " err - error conditions\n"
  70. " warn - warning conditions\n"
  71. " notice - normal but significant condition\n"
  72. " info - informational\n"
  73. " debug - debug-level messages\n";
  74. printf("%s\n", help_msg);
  75. }
  76. /**
  77. * @brief 打印dmesg错误使用的信息
  78. */
  79. void print_bad_usage_msg()
  80. {
  81. const char *bad_usage_msg = "dmesg: bad usage\nTry 'dmesg --help' for more information.";
  82. printf("%s\n", bad_usage_msg);
  83. }