linux-sysprog · advanced · ~15 min
`pipe`, `read`, `write`, and the discipline of closing every fd you open.
Send a message through a pipe and read it back out, exercising the read/write/close discipline.
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.
msg: the NUL-terminated message to send through the pipe (may be empty).out / out_sz: a writable buffer and its size in bytes.Returns 0 on success, -1 on error. After the call out holds the bytes read from the pipe, NUL-terminated.
pipe_roundtrip("hello", buf, n) -> buf = "hello", returns 0
pipe_roundtrip("", buf, n) -> buf = ""
A message msg and a writable buffer out of out_sz bytes.
0 on success, -1 on error; out holds the bytes read, NUL-terminated.
Close the write end before reading; close all descriptors before returning.
#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.