pipe.c

(plain text)
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
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>

void die (const char *msg);

int main () {
  int filedes[2];
  pid_t childpid;

  if (pipe(filedes) == -1) die("pipe() failed");

  switch ( (childpid = fork()) ) {
  case -1: die("fork() failed");

  case 0:
    {
      char buf[80];
      int len;

      close(filedes[STDOUT_FILENO]);
      len = read(filedes[STDIN_FILENO], buf, sizeof(buf));
      if (len < 1) die("read() failed");
      printf("<%d> %d says : \"%.*s\"\n", getpid(), getppid(), len, buf);
      close(filedes[STDIN_FILENO]);
      exit(0);
    }

  default:
    {
      char buf[80];

      close(filedes[STDIN_FILENO]);

      fprintf(stdout, "<%d> Enter a message for %d: ", getpid(), childpid);
      fflush(stdout);
      if (!fgets(buf, 80, stdin)) die("fgets() failed");
      write(filedes[STDOUT_FILENO], buf, strlen(buf) - 1);
      close(filedes[STDOUT_FILENO]);
      wait(0);
    }

    break;
  }

  return 0;
}

void die (const char *msg) {
  perror(msg);
  exit(EXIT_FAILURE);
}