linux-sysprog · advanced · ~15 min

Pipe roundtrip

`pipe`, `read`, `write`, and the discipline of closing every fd you open.

Challenge

Send a message through a pipe and read it back out, exercising the read/write/close discipline.

Task

Implement int pipe_roundtrip(const char *msg, char *out, size_t out_sz) that creates a pipe, writes msg to the write end, reads from the read end into out (NUL-terminating it), closes every file descriptor, and returns 0 on success. No main — the grader calls it.

Input

  • msg: the NUL-terminated message to send through the pipe (may be empty).
  • out / out_sz: a writable buffer and its size in bytes.

Output

Returns 0 on success, -1 on error. After the call out holds the bytes read from the pipe, NUL-terminated.

Example

pipe_roundtrip("hello", buf, n)   ->   buf = "hello", returns 0
pipe_roundtrip("", buf, n)        ->   buf = ""

Edge cases

  • Empty message round-trips to an empty string.

Rules

  • Close the write end before reading (otherwise the read can block). Close all descriptors before returning.

Input format

A message msg and a writable buffer out of out_sz bytes.

Output format

0 on success, -1 on error; out holds the bytes read, NUL-terminated.

Constraints

Close the write end before reading; close all descriptors before returning.

Starter code

#include <unistd.h>
#include <string.h>
#include <stddef.h>

int pipe_roundtrip(const char *msg, char *out, size_t out_sz) {
    /* TODO */
    return -1;
}

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