Initial public busybox maemo commit, 3:1.10.2.legal-1osso12
[busybox4maemo] / 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 Fischer <rep.nop@aon.at>
8  *
9  * Licensed under GPLv2, see file LICENSE in this tarball for details.
10  */
11
12 #include <sys/klog.h>
13 #include "libbb.h"
14
15 int dmesg_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
16 int dmesg_main(int argc ATTRIBUTE_UNUSED, char **argv)
17 {
18         int len;
19         char *buf;
20         char *size, *level;
21         int flags = getopt32(argv, "cs:n:", &size, &level);
22
23         if (flags & 4) {
24                 if (klogctl(8, NULL, xatoul_range(level, 0, 10)))
25                         bb_perror_msg_and_die("klogctl");
26                 return EXIT_SUCCESS;
27         }
28
29         len = (flags & 2) ? xatoul_range(size, 2, INT_MAX) : 16384;
30         buf = xmalloc(len);
31         len = klogctl(3 + (flags & 1), buf, len);
32         if (len < 0)
33                 bb_perror_msg_and_die("klogctl");
34         if (len == 0)
35                 return EXIT_SUCCESS;
36
37         /* Skip <#> at the start of lines, and make sure we end with a newline. */
38
39         if (ENABLE_FEATURE_DMESG_PRETTY) {
40                 int last = '\n';
41                 int in = 0;
42
43                 do {
44                         if (last == '\n' && buf[in] == '<')
45                                 in += 3;
46                         else {
47                                 last = buf[in++];
48                                 bb_putchar(last);
49                         }
50                 } while (in < len);
51                 if (last != '\n')
52                         bb_putchar('\n');
53         } else {
54                 full_write(STDOUT_FILENO, buf, len);
55                 if (buf[len-1] != '\n')
56                         bb_putchar('\n');
57         }
58
59         if (ENABLE_FEATURE_CLEAN_UP) free(buf);
60
61         return EXIT_SUCCESS;
62 }