如何将多条记录从父母的叉子传递给孩子
我想要做的是,我有一个父母和子女的过程。我尝试读取文件并将所有内容传递给孩子。输入文件中有记录。我必须一次读一遍,然后传给孩子。但不管我做什么。孩子只读第一个记录,而不是所有其他记录。我测试了我的方法从输入文件获取所有记录,但不能将它们全部写入子项。请任何想法。如何将多条记录从父母的叉子传递给孩子
struct product_record {
int idnumber; // Unique identification
char name[PRODUCTSIZE]; // String description
double price; // Unit cost
};
int pid, mypipe[2], status;
int main(int argc, char **argv)
{
int result;
result = pipe(mypipe);//create pipes
if (result < 0) {
perror("pipe creation error");//failure in creating a pipe
exit (1);
}//if
if ((pid = fork()) == 0)
{
read(mypipe[0], &product, sizeof(product));
exit(0);
}
else if (pid == -1)
{
cout << "Fork failed" << endl;
exit(1);
}
else
{//parent
parentReadsFromTheFile(argv);//argv inputfile name
wait(&status);
}
return 0;//Return to the OS.
}//main
void parentReadsFromTheFile(char **args)
{
while (getline(inputFile, line)) //read a line till EOF
{
//put read record into product
write(mypipe[1], &product, sizeof(product));//Write to pipe
}
}
可以从过程到另一个传输通过管道的数据,但是这个数据只能包含标量信息:不能传送地址或指针这样。
我怀疑你的product
对象不是一个简单的结构,只有数字和字符。
从您发布的product
的类型可以这种方式传输此类型。
重读你的代码,我看到孩子只读取一条记录:
if ((pid = fork()) == 0) {
read(mypipe[0], &product, sizeof(product));
exit(0);
}
你写:不管我做什么。孩子只读第一个记录,而不是所有其他记录。,但这正是你所做的!
事实上,请注意read
可能会在您应该支持的某些条件下返回短计数,但在目前的情况下,您只会尝试读取单个结构并退出该过程。父进一步写入管道将失败。
的原因,你的“孩子只读取第一个记录,不是所有的人的”,是因为你exit()
读了一遍后立即:
if ((pid = fork()) == 0)
{
read(mypipe[0], &product, sizeof(product));
exit(0);
}
“是因为你在阅读一次后立即退出():”我删除了退出。仍然没有解决/ – user2934615
@ user2934615:删除exit()显然是不够的。你必须编写能够读取其余记录的代码,它本身不会执行它... –
正确地调整你的代码,就不做评论了明显的。 – chqrlie
发布'product'的定义。 – chqrlie
我编辑和解释得更好。谢谢。 – user2934615