linux-sysprog · intermediate · ~15 min

Parse thread count

Reuse the labelled-field parsing pattern.

Challenge

Reuse the find-the-label-then-parse-the-number pattern on the same /proc/<pid>/status text — this time for the thread count.

Task

Implement int parse_threads(const char *status) that finds the Threads: line and returns its integer value.

Input

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

Output

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

Example

parse_threads("Name:\tcat\nVmRSS:\t10 kB\nThreads:\t7\n")   ->   7
parse_threads("Name:\tx\n")                                   ->   -1

Edge cases

  • Threads: absent: return -1.

Input format

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

Output format

The Threads value, 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>

int parse_threads(const char *status) {
    /* TODO */
    return -1;
}

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