c++ - 平行叉管

标签 c++ c fork pipe

void doWork(){

  int fd[2];
  int pret = pipe(fd);

  close(0);
  close(1);
  int dret = dup2(fd[1], 1);
  close(fd[1]);

  while(1){

    char buf[256];
    system("whoami");
    int rret = read(fd[0], buf, 256);

    if(/* something interesting */){
      return;
    }
  }
}

int main(int argc, char* argv[]){

  int children = 2;

  for(unsigned work = 0; work < children; ++work){

    pid_t pid = fork();

    if(pid == 0){
      doWork();
      break;
    }
  }
  int status;
  wait(&status);

  return 0;
}

这个例子有什么问题?我试图让每个子进程调用一个外部程序,然后从管道中读取该程序的输出。我的代码仅在 children 设置为 1 时有效。

编辑:我正在尝试使用 fork/pipes 实现任务并行。父进程和子进程之间没有通信。每个子进程执行一个外部程序,读取输出,处理输出,并继续直到找到所需的输出。

最佳答案

您需要在 fork() 之前创建管道,而不是之后。在您的代码中,只有子进程才会有管道。您需要两个进程来共享它。

例如:

int fd[2];
pid_t pid;

if (pipe(fd)) { /* TODO: handle error */ }

pid = fork();
if (pid < 0) { /* TODO: handle error */ }

if (pid == 0)
{
   /* We are the child.  Set fd[1] as stdout. */
   if (dup2(fd[1], 1)) { /* TODO: handle error */ }

   /* Close fd[0]; this process doesn't need it. */
   close(fd[0]);

   do_work();
   exit(0);
} 
else
{
   /* We are the parent... */
   /* Close the other guy's write fd. */
   close(fd[1]);

   /* Now read from fd[0] */
   /* Possibly waitpid() on child pid, etc. */
}

此外:我喜欢在 fork() 之前调用 fflush(stdout);。否则您将观察到 printf() 的奇怪行为。

关于c++ - 平行叉管,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4898294/

相关文章:

c - 套接字缓冲区大小不增加

c - 在后台 C linux 中运行一个新的子进程

c - 无法让我的代理服务器向客户端发送http请求的信息 - Socket编程

c++ - 为什么我不能递增 std::unordered_map 迭代器?

c - 搜索不起作用需要一些建议

c++ - C++ 编译器实际上是如何传递引用参数的?

c - OpenMP 4.0 的卸载指令

c - 如何在 SIGINT 上仅终止前台子进程?

c++ - 从 map 上检查范围的最佳方法

c++ - 结构引用编译错误 : expected identifier or ‘(’ before ‘&’ token