【问题标题】:How to tell which pipe was written to first如何判断首先写入哪个管道
【发布时间】:2016-03-02 00:19:54
【问题描述】:

所以我有一些我正在编写的代码,我将派出 N 个孩子来处理 N 个不同的文件并收集一些信息。家长只看书,孩子只写字。如果一个孩子先于另一个完成,我想开始在父母中处理该数据,而其他人仍在运行。

我在这里制作了 N 个管道

int pipefds[nFiles*2];
int k;
for(k = 0; k < nFiles; k++)
{
    if(pipe(pipefds[k*2]))
    {
     /* pipe failed */
    }
}

然后我 fork N 个进程,并希望它们对文件执行某些操作并将其发送给父进程

int i;
for(i = 0; i < nFiles; i++)
{
  pid = fork();
  if(pid < 0)
  {
    /* error */
  }
  else if(pid == 0)
  {
    /*child */

    close(pipefds[i*2]); //I think I want to close the Read End of each child's pipe
    getData(file[i]); // do something with the file this process is handling
    write(fd[i*2 +1], someData, sizeof(someData); // write something to the write end of the child's pipe
    exit(0);
  }
  else
  {
   /*parent*/
   if(i = nFiles -1) //do I have to make this condition so that I start once all processes have been started??
    {
      int j;
      for(j = 0; j < nFiles; j++)
      {
       close(pipefds[j*2+1]); //close all the parents write ends
      }
      /*Here I want to pick the pipe that finished writing first and do something with it */
    } 
  }

我是否必须等待 for 循环的最后一次迭代才能开始执行父级操作(因为我希望在执行任何操作之前启动所有进程)?另外,如何在 pipefds 中找到已完成写入的管道,以便我可以在其他人运行时开始处理它?谢谢!

【问题讨论】:

  • C,很抱歉造成混乱

标签: c process pipe fork


【解决方案1】:

可能最简单的解决方案是先创建所有的孩子。然后围绕pollselect 运行一个单独的循环。当您在其中一个管道末端获得读取命中时,将数据读入缓冲区。如果该读取指示管道的另一端已关闭,您可以开始处理来自该子节点的数据。 (不要忘记从你正在使用polling 或selecting 的集合中移除该管道。)当所有子管道都关闭时,你就完成了。

【讨论】:

    猜你喜欢
    • 2011-10-05
    • 2022-10-12
    • 2019-04-28
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多