1 /* dmesg.c - display/control kernel ring buffer. 2 * 3 * Copyright 2006, 2007 Rob Landley <rob (at) landley.net> 4 * 5 * http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/dmesg.html 6 7 // We care that FLAG_c is 1, so keep c at the end. 8 USE_DMESG(NEWTOY(dmesg, "trs#<1n#c[!tr]", TOYFLAG_BIN)) 9 10 config DMESG 11 bool "dmesg" 12 default y 13 help 14 usage: dmesg [-c] [-r|-t] [-n LEVEL] [-s SIZE] 15 16 Print or control the kernel ring buffer. 17 18 -c Clear the ring buffer after printing 19 -n Set kernel logging LEVEL (1-9) 20 -r Raw output (with <level markers>) 21 -s Show the last SIZE many bytes 22 -t Don't print kernel's timestamps 23 */ 24 25 #define FOR_dmesg 26 #include "toys.h" 27 #include <sys/klog.h> 28 29 GLOBALS( 30 long level; 31 long size; 32 ) 33 34 void dmesg_main(void) 35 { 36 // For -n just tell kernel to which messages to keep. 37 if (toys.optflags & FLAG_n) { 38 if (klogctl(8, NULL, TT.level)) perror_exit("klogctl"); 39 } else { 40 char *data, *to, *from; 41 int size; 42 43 // Figure out how much data we need, and fetch it. 44 size = TT.size; 45 if (!size && 1>(size = klogctl(10, 0, 0))) perror_exit("klogctl");; 46 data = to = from = xmalloc(size+1); 47 size = klogctl(3 + (toys.optflags & FLAG_c), data, size); 48 if (size < 0) perror_exit("klogctl"); 49 data[size] = 0; 50 51 // Filter out level markers and optionally time markers 52 if (!(toys.optflags & FLAG_r)) while ((from - data) < size) { 53 if (from == data || from[-1] == '\n') { 54 char *to; 55 56 if (*from == '<' && (to = strchr(from, '>'))) from = ++to; 57 if ((toys.optflags&FLAG_t) && *from == '[' && (to = strchr(from, ']'))) 58 from = to+1+(to[1]==' '); 59 } 60 *(to++) = *(from++); 61 } else to = data+size; 62 63 // Write result. The odds of somebody requesting a buffer of size 3 and 64 // getting "<1>" are remote, but don't segfault if they do. 65 if (to != data) { 66 xwrite(1, data, to-data); 67 if (to[-1] != '\n') xputc('\n'); 68 } 69 if (CFG_TOYBOX_FREE) free(data); 70 } 71 } 72