1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// !> 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;
}