所以,这是我之前发布的作业的后续跟进。 链接:https://stackoverflow.com/questions/42913617/piping-and-forking-in-c-in-unix
现在这部分代码都工作了,但是现在我必须转到4个进程,这给了我很多时间。就像回顾一样,我必须获取数据文件,并使用管道和分叉将总和加起来。目前我遇到了问题,如果我把int mypipe [4]并相应地改变我的所有变量,我的程序冻结了。目前尝试两个管道,但只显示其中一个管道的总和。这是我对4个流程部分的代码:
else
{
pid_t child1, child2, child3, child4;
int mypipe1[2];
int mypipe2[2];
//File 1
t1=clock();
int temptotal=0;
int file1[1000];
for(int i = 0; i < 1000; i++)
{
infile1 >> file1[i];
}
pipe(mypipe1);
pipe(mypipe2);
//Begin the forking
if((child1 = fork()) == 0)
{
close(mypipe1[1]);
close(mypipe2[0]);
close(mypipe2[1]);
for(int i = 0; i < 250; i++)
{
temptotal = temptotal + file1[i];
}
write(mypipe1[0], &temptotal, sizeof(temptotal));
temptotal=0;
exit(0);
}
else
{
if((child2 =fork())==0)
{
close(mypipe1[0]);
close(mypipe2[1]);
close(mypipe2[0]);
for(int i =250; i < 500; i++)
{
temptotal = temptotal + file1[i];
}
write(mypipe1[1], &temptotal, sizeof(temptotal));
temptotal=0;
exit(1);
}
else
{
if((child3=fork())==0)
{
close(mypipe1[0]);
close(mypipe1[1]);
close(mypipe2[1]);
for(int i =500; i < 750; i++)
{
temptotal = temptotal + file1[i];
}
write(mypipe2[0], &temptotal, sizeof(temptotal));
temptotal=0;
exit(0);
}
else
{
if((child4=fork())==0)
{
close(mypipe1[0]);
close(mypipe1[1]);
close(mypipe2[0]);
for(int i =750; i < 1000; i++)
{
temptotal = temptotal + file1[i];
}
write(mypipe2[1], &temptotal, sizeof(temptotal));
temptotal=0;
exit(1);
}
else
{
//Parent Proccess
int n1,n2,n3,n4;
read(mypipe1[0],&n1,sizeof(n1));
close(mypipe1[0]);
read(mypipe1[1],&n2,sizeof(n2));
close(mypipe1[1]);
read(mypipe2[0],&n3,sizeof(n3));
close(mypipe2[0]);
read(mypipe2[1],&n4,sizeof(n4));
close(mypipe2[1]);
total = n1+n2+n3+n4;
std::cout<<"File1 sum: "<<total<<std::endl;
}
}
}
}
}
我缺少什么想法?任何输入都非常感谢!
答案 0 :(得分:0)
pipe(mypipe1);
pipe(mypipe2);
您在这里创建管道。稍后在代码中:
write(mypipe1[0], &temptotal, sizeof(temptotal));
// ...
read(mypipe1[1],&n2,sizeof(n2));
你已经倒退了。
pipe()
将管道的 读取 一侧放入数组的第一个元素#0, 写入< / em> 管道的一侧进入阵列#1的第二个元素。 mypipe1[0]
是管道的读取端。 mypipe1[1]
是管道的写入端。
您的代码尝试从每个管道的写入端读取,并写入每个管道的读取端。
而且您不知道问题是什么,因为您的代码未能认真检查来自read()
或write()
的返回值。如果你这样做了,你会发现自己所有的read()
和write()
都在向你喊叫,告诉你他们失败了。
您今天学到的经验是:始终检查错误代码并从系统调用中返回值,以便您确切知道问题何时发生,以及为什么,而无需在stackoverflow.com上寻求帮助
这可能不是您的代码唯一的问题,但如果您修复它,并且您为所有其他系统调用添加了正确的错误检查,您应该能够轻松找到并解决任何剩余的问题。