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