Simvik

Read the kernel command line

Find a parameter's value, or whether a flag is present, in the boot arguments. An easy embedded C problem (The Linux boot process), run and graded in the…

easy · The Linux boot process · linux · boot · parsing

The bootloader passes the Linux kernel a command line (/proc/cmdline shows it afterwards): space-separated parameters, either key=value or a bare flag, for example:

console=ttyS0,115200 root=/dev/mmcblk0p2 rootwait rw quiet

Write cmdline_get(cmdline, key, value, size): if key= appears as a whole parameter, copy its value (up to the next space; at most size - 1 characters) and return 1; if key appears as a bare flag, set value to an empty string and return 1; otherwise return 0. If a key appears more than once, the last one wins, as in the kernel.

Starter code

int cmdline_get(const char *cmdline, const char *key, char *value, int size) {
  const char *p = strstr(cmdline, key);
  if (!p) return 0;
  p += strlen(key) + 1;
  int n = 0;
  while (*p && *p != ' ' && n < size - 1) value[n++] = *p++;
  value[n] = 0;
  return 1;
}

Example tests

Values

show("console");
show("root");

Expected output:

console: "ttyS0,115200"
root: "/dev/mmcblk0p2"

Flags and missing keys

show("rootwait");
show("ro");

Expected output:

rootwait: ""
ro: not set

Learn it first