linux-sysprog · intermediate · ~15 min

Parse VmRSS from /proc status

Extract a labelled field from /proc text.

Challenge

A /proc/<pid>/status file is line-oriented text with Label:\tvalue fields. Scrape the resident-memory field out of it.

Task

Implement long parse_vmrss_kb(const char *status) that finds the VmRSS: line and returns its value in kB.

Input

  • status: the full text of a /proc/<pid>/status file (lines like VmRSS:\t1234 kB).

Output

The integer after VmRSS: (skip any spaces/tabs), or -1 if there is no VmRSS: field.

Example

parse_vmrss_kb("Name:\tcat\nVmRSS:\t1234 kB\nThreads:\t3\n")   ->   1234
parse_vmrss_kb("Name:\tx\n")                                     ->   -1

Edge cases

  • VmRSS: absent: return -1.

Input format

status: text of a /proc//status file.

Output format

VmRSS value in kB, or -1 if the field is absent.

Constraints

Skip whitespace after the label before parsing the number.

Starter code

#include <string.h>
#include <stdlib.h>

long parse_vmrss_kb(const char *status) {
    /* TODO */
    return -1;
}

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.