0
我所做的是我创建了n个孩子,并且父母使用n个管道向他们发送了“开始”消息。每个孩子一个管道。现在我正在努力做的事情是将父母的数量发回给每个孩子。N个孩子向父母发送消息
这是我的代码至今:
int main()
{
int n=5;
int p[n-1][2];
int i;
for(i=0;i<n;i++){
if(pipe(p[i])>0){
perror("pipe error");
exit(1);
}
}
for(i=0;i<n;i++){
pid_t pid=fork();
if(pid<0){
perror("fork error");
exit(1);
}
if(pid==0){
int j;
for(j=0;j<n;j++){
close(p[j][1]);
}
for(j=0;j<i;j++){
close(p[j][0]);
}
char msg[256];
int h;
read(p[i][0],&h,sizeof(int));
read(p[i][0],msg,h*sizeof(char));
cout<<i<<"_"<<msg<<endl;
close(p[i][0]);//here I would like to send the number i to the parent
for(j=i+1;j<n;j++){
close(p[j][0]);
}
exit(0);
}
}
char ms[256];
strcpy(ms,"start");
int ho=strlen(ms);
for(i=0;i<n;i++){
if(write(p[i][1],&ho,sizeof(int))==-1){
perror("write error");
exit(1);
}
if(write(p[i][1],ms,ho*sizeof(ms))==-1){
perror("write error");
exit(1);
}
close(p[i][1]);
}
for(int j=0;j<n;j++)
close(p[j][0]);//then read the number of each child and print it
while(wait(NULL)>0){};
exit(0);
}
这是输出:
0_start
2_start
1_start
4_start
3_start
所以我成功发送的消息开始到各child.But我可以我们不知道父母如何接收孩子们发送的号码。
数组p的大小为n。所以你应该通过'p [n-1]'写入'p [0]'。你正在通过'p [n]'给'p [1]'写信。 –
将您的循环更改为'for(int j = 0; j
好吧我会编辑 –