Friday, September 30, 2011

Pipe a chain of processes

Create a chain of processes which are piped hand by hand, and write whatever read from stdin of the beginning process to stdout of the ending process.


#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <unistd.h>


using namespace std;

int main() {
 
  // make sure at least one command

  int fd[10][2];

  pid_t pid;

  int i = 0;

  int count = 0;

  char c;

  for (; i < 4; ++i) {
    pipe (fd[i]);
   
    pid = fork();
   
    if (pid == 0) {
      dup2 (fd[i][0], 0);

      if (i > 0) {
dup2 (fd[i-1][1], 1);
      }
      else {
close (fd[i][1]);
      }

      while ((count = read(0, &c, 1)) > 0)
write(1, &c, 1);
     
      cout << "this is child process " << i << endl;

      break;
    }
    else {
      cout << "this is parent process " << i << endl;

      continue;
    }
  }
 
  if (pid) {
    close (fd[i-1][0]);

    while ((count = read(0, &c, 1)) > 0)
      write(1, &c, 1);
   
    cout << "this is final parent " << endl;
   
    waitpid (pid, NULL, 0);
  }

  return 0;
}

No comments:

Post a Comment