linux-sysprog · beginner · ~10 min
Parse and validate a small bracketed integer prefix.
Read the <PRI> prefix at the start of a syslog line and extract the severity level (the low 3 bits of the priority value).
Implement int syslog_severity(const char *line) that returns the syslog severity, or -1 on malformed input.
line: a syslog line that should begin with <PRI>, where PRI = facility * 8 + severity and is in the range 0–191.Returns the severity, computed as PRI % 8 (a value 0–7). Returns -1 if the line does not start with <, has no digits after <, has more than 3 digits, has no closing >, or has PRI > 191 (also -1 for a NULL line).
syslog_severity("<34>Oct 11 host app") -> 2 (34 % 8)
syslog_severity("<0>x") -> 0
syslog_severity("<191>x") -> 7
syslog_severity("34>x") -> -1 (no '<')
syslog_severity("<>x") -> -1 (no digits)
syslog_severity("<999>x") -> -1 (PRI > 191)
syslog_severity("<12") -> -1 (no closing '>')
syslog_severity(NULL) -> -1
NULL all return -1.Every syslog line starts with <PRI>; severity = PRI mod 8. Triage pipelines read it constantly.
A syslog line beginning with
The severity PRI % 8 (0-7), or -1 if the prefix is malformed or PRI > 191.
Require a leading '<', 1-3 digits, a closing '>', and PRI <= 191; otherwise -1.
int syslog_severity(const char *line) {
/* TODO */
(void)line;
return -1;
}
Forgetting the closing '>'. Allowing PRI > 191. Not capping digit count.
PRI 0 and 191 (the extremes). Missing bracket. Overlong number.
O(1).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.