【问题标题】:IPC using pipes?IPC使用管道?
【发布时间】:2014-06-24 20:25:23
【问题描述】:

我正在尝试使用管道实现一个程序,其中父进程接受一个字符串并将其传递给子进程。只需要单管即可。管道如何读写接受字符串。

这是我的示例代码!全部!

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

【问题讨论】:

  • revredstrbuf 的用途是什么?看起来这些混淆的名称是造成问题的原因。
  • 是的,一切都好!请问您有什么特别的问题?
  • 为什么标记为 C?

标签: c++ unix pipe named-pipes


【解决方案1】:

您永远不会将要反转的字符串传递给孩子,因此它会反转一些随机垃圾并将其发送给父母。

小问题:

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

您不想在孩子中从main return 的原因是您不知道会产生什么后果。您可以调用退出处理程序来操作父级期望保持不变的真实世界对象。

【讨论】:

  • 如何将字符串传递给孩子?
  • @user3767923 仔细检查您的代码。您有一个进程立即复制str,而另一个进程最终初始化它。
  • 我需要做什么,添加 sleep() 会有帮助吗?
  • @user3767923 这取决于你想做什么。也许您想为另一个方向创建第二个管道?也许您想在调用fork 之前输入字符串?不幸的是,sleep() 无济于事。这不是竞争条件。您只是忘记将字符串传递给孩子。
  • 这可能是因为大多数平台上的管道都是双向的。但它不能保证工作——管道可以是单向的。也许你应该从管道切换到保证双向的东西。 (UNIX 域流套接字?)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-31
  • 1970-01-01
  • 1970-01-01
  • 2011-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多