ubase

suckless linux base utils
git clone git://git.2f30.org/ubase
Log | Files | Refs | README | LICENSE

dmesg.c (1325B)


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