【发布时间】:2016-06-22 08:03:09
【问题描述】:
我有一个任务,我必须创建 n 个孩子。父母会给他们每个人一个单词。他们会修改并打印它。我尝试为每个孩子创建管道,然后向每个孩子发送一个单词。但这是我的程序的输出:
1 child begins
2 child begins
1 child ends
3 child begins
4 child begins
2 child ends
5 child begins
3 child ends
4 child ends
5 child ends
End parent
这是我的程序:
int main()
{
ifstream f("in.txt");
int n=5;//n children
int p[n][2];
for(int i=0;i<n;i++)
if(pipe(p[i])<0){
perror("pipe error");
exit(1);
}
for(int i=0;i<n;i++)
{
pid_t pid=fork();
if(pid<0){
perror("fork error");
exit(1);
}
if(pid==0){//i child
for(int j=0;j<=i;j++)
close(p[j][1]);
char word[256];
int size;
cout<<i+1<<" child begins"<<endl;
while(read(p[i][0],&size,sizeof(int))>0){//first I get the size of the word
read(p[i][0],word,size*sizeof(char));//then the word
word[i%(size-1)] = '-';//make some changes to it
cout<<i+1<<"child "<<word<<endl;}
cout<<i+1<<" child ends"<<endl;
exit(0);
}
if(pid>0){
close(p[i][0]);
}
}
char word[100];
int size;
int j=0;
while(f>>word){
size=strlen(word);
write(p[j][1],&size,sizeof(int));
write(p[j][1],word,100);
j++;
}
for(int i=0;i<n;i++)
close(p[i][1]);
while(wait(NULL) > 0){};
cout<<"End parent"<<endl;
exit(0);
}
【问题讨论】:
-
我认为您应该将其标记为 C++,而不是 C。
-
write(p[j][0]应该是write(p[j][1]。 -
您在为管道声明二维数组时到底有什么意义?这是一个正确的方法吗?如果是,请解释检查该管道的单维错误情况背后的座右铭。
-
p[i][0] 将是第 i 个孩子的读取端,p[i][1] 将是孩子的写入端