linux-sysprog · beginner · ~15 min

Count pipeline stages

Relate pipe symbols to process count.

Challenge

In a shell pipeline, each | connects two commands, so the number of stages (processes) is the count of | plus one — except an empty line runs nothing.

Task

Implement int pipeline_stages(const char *cmd) that returns the number of pipeline stages: the count of '|' characters plus one, or 0 for an empty string.

Input

  • cmd: a command string, possibly containing '|' separators.

Output

Number of stages: 0 if cmd is empty, otherwise (count of '|') + 1.

Example

pipeline_stages("ls")      ->   1
pipeline_stages("ls|wc")   ->   2
pipeline_stages("a|b|c")   ->   3
pipeline_stages("")        ->   0

Edge cases

  • Empty string: return 0 (not 1).

Input format

cmd: command string, may contain '|' separators.

Output format

0 if empty, else (number of '|') + 1.

Constraints

An empty string has 0 stages.

Starter code

int pipeline_stages(const char *cmd) {
    /* TODO */
    return 0;
}

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