// !> A basic demonstration of a pipe [fv]
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <wait.h>
#include <stdio.h>
#include <assert.h>
int main(int argc, char **argv) {
int pipe_fd[2];
// create a pipe:
// pipe_fd[0] is the _read_ end
// pipe_fd[1] is the _write_ end
assert(pipe(pipe_fd) != -1);
pid_t reading_child = fork();
assert(reading_child != -1);
if (reading_child == 0) {
// both parent and child share both ends, so we'll just close the end we
// don't use
close(pipe_fd[1]);
char buf[256];
int bytes = read(pipe_fd[0], buf, 255);
buf[bytes] = '\0';
printf("Received %d bytes from parent: '%s'\n", bytes, buf);
return 0;
}
// both parent and child share both ends, so we'll just close the end we
// don'tuse
close(pipe_fd[0]);
write(pipe_fd[1], "Hello, child!", 13);
wait(NULL);
return 0;
}