【问题标题】:fork n children and send them a wordfork n 个孩子并给他们发消息
【发布时间】: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] 将是孩子的写入端

标签: c++ linux pipe fork


【解决方案1】:

在您的原始帖子中,您错误地写入了父代码中管道的读取端。我看到你现在已经改变了 - 相关行来自:

write(p[j][0],&size,sizeof(int));
write(p[j][0],word,100);

收件人:

write(p[j][1],&size,sizeof(int));
write(p[j][1],word,100);

此外,您的字长并没有真正做到正确。我建议进行这些进一步的更改,以便在读取结束时出现的单词正确地以 null 结尾并且没有尾随垃圾:

write(p[j][1],&size,sizeof(int));
write(p[j][1],word,size+1);

我能够重新创建您的原始问题,并使用这些更改测试了代码,并且它可以按您的预期工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    相关资源
    最近更新 更多