linux-sysprog · advanced · ~15 min

Fork+exec /bin/echo

`execvp` semantics: image replacement; the only way back is via the exit status.

Challenge

Run the external echo program from C by forking and replacing the child with execvp.

Task

Implement int run_echo(const char *msg) that forks, has the child run echo msg via execvp("echo", argv), waits for the child in the parent, and returns the child's exit status. No main — the grader calls it.

Input

One argument msg: the string to pass to echo as its single argument.

Output

The child's exit status as an int (0 on a successful run), or -1 on a fork/wait error. The child prints msg followed by a newline to stdout (the harness captures it via a pipe; the parent itself does no I/O).

Example

run_echo("hi")   ->   returns 0; child prints "hi\n"

Edge cases

  • If execvp fails, the child should _exit(127) so the parent can detect it.

Rules

  • The argv array must be NUL-terminated, with argv[0] = "echo". Use execvp so PATH is searched.

Input format

One argument msg: the string to pass to echo.

Output format

The child's exit status as an int (0 on success), or -1 on error.

Constraints

argv must be NUL-terminated with argv[0]="echo"; use execvp; child _exit(127) on exec failure.

Starter code

#include <unistd.h>
#include <sys/wait.h>

int run_echo(const char *msg) {
    /* TODO */
    return -1;
}

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