平行叉管

Arl*_*len 0 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

asv*_*kau 6

您需要先创建管道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. */
}
Run Code Online (Sandbox Code Playgroud)

另外:我喜欢fflush(stdout);在我之前打电话fork().否则你会观察到奇怪的行为printf().