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