summaryrefslogtreecommitdiffstats
path: root/toolbox/dmesg.c
blob: 9c73b00ca3ea0551fd9fa143d4d95db04e088c29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/klog.h>
#include <string.h>

#define FALLBACK_KLOG_BUF_SHIFT	17	/* CONFIG_LOG_BUF_SHIFT from our kernel */
#define FALLBACK_KLOG_BUF_LEN	(1 << FALLBACK_KLOG_BUF_SHIFT)

int dmesg_main(int argc, char **argv)
{
    char *buffer;
    char *p;
    ssize_t ret;
    int n, op, klog_buf_len;

    klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0);

    if (klog_buf_len <= 0) {
        klog_buf_len = FALLBACK_KLOG_BUF_LEN;
    }

    buffer = (char *)malloc(klog_buf_len + 1);

    if (!buffer) {
        perror("malloc");
        return EXIT_FAILURE;
    }

    p = buffer;

    if((argc == 2) && (!strcmp(argv[1],"-c"))) {
        op = KLOG_READ_CLEAR;
    } else {
        op = KLOG_READ_ALL;
    }

    n = klogctl(op, buffer, klog_buf_len);
    if (n < 0) {
        perror("klogctl");
        return EXIT_FAILURE;
    }
    buffer[n] = '\0';

    while((ret = write(STDOUT_FILENO, p, n))) {
        if (ret == -1) {
	    if (errno == EINTR)
                continue;
	    perror("write");
	    return EXIT_FAILURE;
	}
	p += ret;
	n -= ret;
    }

    return 0;
}