Monday, 13 July 2015

//program for string reverse using pipe lines 

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

using namespace std;

int main()
{
  int pid[2];
  ssize_t fbytes;
  pid_t childpid;
  char str[20], rev[20];
  char buf[20], red[20];

  pipe(pid);

  if ((childpid = fork()) == -1) {
    perror("Fork");
    return(1);
  }

  if (childpid == 0) {
    // child process close the input side of the pipe
    close(pid[0]);

    int i = -1, j = 0;
    while (str[++i] != '\0') {
      while(i >= 0) {
        rev[j++] = str[--i];
      }
      rev[j] = '\0';
    }

    // Send reversed string through the output side of pipe
    write(pid[1], rev, sizeof(rev));
    close(pid[0]);
    return(0);
  } else {
    cout << "Enter a String: ";
    cin.getline(str, 20);

    // Parent process closing the output side of pipe.
    close(pid[1]);

    // reading the string from the pipe
    fbytes = read(pid[0], buf, sizeof(buf));
    cout << "Reversed string: " << buf;
    close(pid[0]);
  }

  return 0;
}

No comments:

Post a Comment