Skip to content

Instantly share code, notes, and snippets.

@ph1ee
Last active August 29, 2015 14:01
Show Gist options
  • Save ph1ee/130a0d33001d53696da2 to your computer and use it in GitHub Desktop.
Save ph1ee/130a0d33001d53696da2 to your computer and use it in GitHub Desktop.
kernel command line parser
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
static int xread(int fd, void* buf, size_t len)
{
int r;
do {
r = read(fd, buf, len);
} while (r < 0 && errno == EINTR);
return r;
}
static int proc_read(const char* filename, char* buf, size_t size)
{
int len = 0;
int fd = open(filename, O_RDONLY);
if (fd < 0) {
return len;
}
len = xread(fd, buf, size - 1);
close(fd);
buf[len > 0 ? len : 0] = 0;
return len;
}
static int parse_cmdline(const char* opt, char* buf, size_t size)
{
char cmdline[1024];
if (proc_read("/proc/cmdline", cmdline, sizeof(cmdline)) > 0) {
struct {
const char* delim;
char* tok, *str, *saveptr;
} ctx[2] = { { " ", NULL, cmdline, NULL }, { "=", NULL, NULL, NULL } };
for (; (ctx[0].tok = strtok_r(ctx[0].str, ctx[0].delim, &ctx[0].saveptr)) != NULL;
ctx[0].str = ctx[0].saveptr) {
ctx[1].str = ctx[0].tok;
for (; (ctx[1].tok = strtok_r(ctx[1].str, ctx[1].delim, &ctx[1].saveptr)) != NULL;
ctx[1].str = ctx[1].saveptr) {
if (!strncmp(opt, ctx[1].tok, strlen(opt))) {
char* val = strtok_r(ctx[1].saveptr, ctx[1].delim, &ctx[1].saveptr);
if (buf) {
buf[val ? size - 1 : 0] = 0;
if (val) {
strncpy(buf, val, size - 1);
}
}
return 1;
}
}
}
}
return 0;
}
int main()
{
int i;
char buf[1024];
const char* opts[] = { "root", "splash", "debug" };
for (i = 0; i < sizeof(opts) / sizeof(*opts); i++) {
if (parse_cmdline(opts[i], buf, sizeof(buf)) > 0) {
printf("%s=%s\n", opts[i], buf[0] > 0 ? buf : "N/A");
}
}
exit(EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment