1 #include <stdlib.h> 2 #include <unistd.h> 3 #include <stdio.h> 4 #include <errno.h> 5 #include <sys/klog.h> 6 #include <string.h> 7 8 #define FALLBACK_KLOG_BUF_SHIFT 17 /* CONFIG_LOG_BUF_SHIFT from our kernel */ 9 #define FALLBACK_KLOG_BUF_LEN (1 << FALLBACK_KLOG_BUF_SHIFT) 10 11 int dmesg_main(int argc, char **argv) 12 { 13 char *buffer; 14 char *p; 15 ssize_t ret; 16 int n, op, klog_buf_len; 17 18 klog_buf_len = klogctl(KLOG_SIZE_BUFFER, 0, 0); 19 20 if (klog_buf_len <= 0) { 21 klog_buf_len = FALLBACK_KLOG_BUF_LEN; 22 } 23 24 buffer = (char *)malloc(klog_buf_len + 1); 25 26 if (!buffer) { 27 perror("malloc"); 28 return EXIT_FAILURE; 29 } 30 31 p = buffer; 32 33 if((argc == 2) && (!strcmp(argv[1],"-c"))) { 34 op = KLOG_READ_CLEAR; 35 } else { 36 op = KLOG_READ_ALL; 37 } 38 39 n = klogctl(op, buffer, klog_buf_len); 40 if (n < 0) { 41 perror("klogctl"); 42 return EXIT_FAILURE; 43 } 44 buffer[n] = '\0'; 45 46 while((ret = write(STDOUT_FILENO, p, n))) { 47 if (ret == -1) { 48 if (errno == EINTR) 49 continue; 50 perror("write"); 51 return EXIT_FAILURE; 52 } 53 p += ret; 54 n -= ret; 55 } 56 57 return 0; 58 } 59