gpt4 book ai didi

c - 如何使用 fork 将多条记录从 parent 传递给 child

转载 作者:太空宇宙 更新时间:2023-11-04 03:31:50 25 4
gpt4 key购买 nike

我想做的是,我有一个父子进程。我尝试读取文件并将所有内容传递给 child 。输入文件中有记录。我必须一次阅读一次并传给 child 。但不管我做什么。 child 只读取第一个记录,而不是所有其他记录。我测试了我的方法从输入文件中获取所有记录但不能将它们全部写入 child 。请有任何想法。

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 发布的类型,可以通过这种方式传输此类型。

重新阅读你的代码,我看到 child 只读了一条记录:

if ((pid = fork()) == 0) {
read(mypipe[0], &product, sizeof(product));
exit(0);
}

你写:无论我做什么。 child 只阅读第一条记录,而不是所有其他记录。,但这正是您所做的!

事实上,请注意 read 在某些您应该支持的情况下可能会返回一个短计数,但在当前情况下,您只尝试读取单个结构并退出过程。父级进一步写入管道将失败。

关于c - 如何使用 fork 将多条记录从 parent 传递给 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35832069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com