dmesg.c (1378B)
1 /* See LICENSE file for copyright and license details. */ 2 #include <sys/klog.h> 3 4 #include <stdio.h> 5 #include <stdlib.h> 6 #include <string.h> 7 #include <unistd.h> 8 9 #include "util.h" 10 11 static void dmesg_show(const void *buf, size_t n); 12 13 enum { 14 SYSLOG_ACTION_READ_ALL = 3, 15 SYSLOG_ACTION_CLEAR = 5, 16 SYSLOG_ACTION_CONSOLE_LEVEL = 8, 17 SYSLOG_ACTION_SIZE_BUFFER = 10 18 }; 19 20 static void 21 usage(void) 22 { 23 eprintf("usage: [-Ccr] [-n level] %s\n", argv0); 24 } 25 26 int 27 main(int argc, char *argv[]) 28 { 29 int n; 30 char *buf; 31 int cflag = 0; 32 long level; 33 34 ARGBEGIN { 35 case 'C': 36 if (klogctl(SYSLOG_ACTION_CLEAR, NULL, 0) < 0) 37 eprintf("klogctl:"); 38 return 0; 39 case 'c': 40 cflag = 1; 41 break; 42 case 'r': 43 break; 44 case 'n': 45 level = estrtol(EARGF(usage()), 10); 46 if (klogctl(SYSLOG_ACTION_CONSOLE_LEVEL, NULL, level) < 0) 47 eprintf("klogctl:"); 48 return 0; 49 default: 50 usage(); 51 } ARGEND; 52 53 n = klogctl(SYSLOG_ACTION_SIZE_BUFFER, NULL, 0); 54 if (n < 0) 55 eprintf("klogctl:"); 56 57 buf = emalloc(n); 58 59 n = klogctl(SYSLOG_ACTION_READ_ALL, buf, n); 60 if (n < 0) 61 eprintf("klogctl:"); 62 63 dmesg_show(buf, n); 64 65 if (cflag && klogctl(SYSLOG_ACTION_CLEAR, NULL, 0) < 0) 66 eprintf("klogctl:"); 67 68 free(buf); 69 return 0; 70 } 71 72 static void 73 dmesg_show(const void *buf, size_t n) 74 { 75 const char *p = buf; 76 ssize_t r; 77 78 r = write(1, p, n); 79 if (r < 0) 80 eprintf("write:"); 81 if (r > 0 && p[r - 1] != '\n') 82 putchar('\n'); 83 }