Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I m trying to implement a program using pipes where parent process accepts a string and passes it to child process. Need to be done with only single pipe. How does the pipe read & write accepts string.

Here is my sample code! all!

#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] != '') {
      while(i >= 0) {
        rev[j++] = str[--i];
      }
      rev[j] = '';
    }

    // 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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

You never pass the string to be reversed to the child, so it reverses some random garbage and sends it to the parent.

Minor issues:

write(pid[1], rev, sizeof(rev));
close(pid[0]); // Should be pid[1]
return(0); // Should be _exit(0)

The reason you don't want to return from main in the child is that you don't know what consequences that will have. You may call exit handlers that manipulate real world objects that the parent expects to remain intact.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...