midmesg/midmesg.c

72 lines
2.1 KiB
C

/* midmesg - Display Linux kernel log information
*
* MIT License
*
* Copyright (c) 2021 Alinur Songül
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE. */
#include <sys/klog.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdarg.h>
#define PROGRAM "midmesg"
#define eprintf(...) fprintf(stderr, __VA_ARGS__)
int main()
{
int kbuf_unread_size;
/* Get the number of all unread bytes in
* the kernel ring buffer */
kbuf_unread_size = klogctl(9, NULL, 0);
if (kbuf_unread_size < 0)
{
eprintf("%s: unable to read log buffer: %s\n",
PROGRAM, strerror(errno));
exit(errno);
}
/* allocate memory for kernel log to be stored in memory */
char* kbuf = (char*)malloc(kbuf_unread_size);
printf("Waiting for klogctl...");
int read_bytes = klogctl(2, kbuf, kbuf_unread_size);
if (read_bytes != -1)
printf("Read %d bytes\n\n", read_bytes);
else {
eprintf("%s\n", strerror(errno));
free(kbuf); /* free up leftover allocated memory */
exit(errno);
}
printf("%s\n", kbuf);
free(kbuf);
return 0;
}