IPC使用管道?

时间:2014-06-24 20:25:23

标签: c++ unix pipe named-pipes

我正在尝试使用管道实现一个程序,其中父进程接受一个字符串并将其传递给子进程。只需要用一根管子就可以完成。管道如何阅读& write接受字符串。

这是我的示例代码!所有!

#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;
}

1 个答案:

答案 0 :(得分:3)

你永远不会将字符串传递给孩子,所以它会反转一些随机垃圾并将其发送给父母。

小问题:

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

您不希望孩子return来自main的原因是您不知道会产生什么后果。您可以调用操作父对象希望保持完整的真实世界对象的退出处理程序。

相关问题