Logo  

CS471/571 - Operating Systems

Displaying ./code/Pipes/pipe.c

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

#define K	1024

/**
 * Send a message from the parent to the child process:
 * pfd[1] -> [pipe] -> pfd[0]
 */

void child(int pfd[2])
{
  // Make sure the write end is closed in the child so it may receive the EOF
  // when the parent closes the write end:
  close(pfd[1]);

  char buf[K];
  int r = read(pfd[0], buf, K);
  if (r < 0) {
    perror("pipe read");
    return;
  }
  write(STDOUT_FILENO, buf, r);
  return;
}


void parent(int pfd[2])
{
  // Close the read end, because we don't need it:
  close(pfd[0]);

  FILE *pipe = fdopen(pfd[1], "w");
  fprintf(pipe, "Hello, child!\n");

  fclose(pipe);
  // Closing this should send the EOF on the pipe:
//  close(pfd[1]);
  // Wait until the child changes its run state (probably dead):
  wait(NULL);
}

int main(void)
{
  int pfd[2];

  if (pipe(pfd) < 0) {
    perror("pipe");
    return 1;
  }

  pid_t pid = fork();

  if (pid < 0) {
    perror("fork");
    return 1;
  }

  if (pid == 0) child(pfd);
  else parent(pfd);

  return 1;
}