【发布时间】: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,很抱歉造成混乱