gpt4 book ai didi

c - 如何使用管道来保留子进程中的值?

转载 作者:太空宇宙 更新时间:2023-11-04 01:32:34 26 4
gpt4 key购买 nike

这是我目前拥有的一段代码:

pipe(pipes);
int count = 0, t = 0;
int forks[numForks];
for(j = 1; j<=numForks; j++){
if((pid=fork()) == 0){
count = findKey(in, key, buf, j, count);
close(pipes[0]);
write(pipes[1],&count, sizeof(count));
exit(0);
}else{
close(pipes[1]);
read(pipes[0], &t, sizeof(t));
}
}
count = t;
printf("count = %i\n", count);

我创造了 n 个 child 。他们在每个 child 中扫描文本文件的不同部分,并返回找到关键字的次数。 children 都只阅读了文本文件的特定部分。有时 child 可能在自己的部分找不到关键字,所以它显然返回 0。在我使用的测试用例中,count 的最终值应该是 1 但最后的最终值是 0,因为我不认为我正在使用管道正确保存每个值。我知道在某个时刻,其中一个 child 确实找到了关键字,因为如果我在 if 语句中的函数调用之后放置一个 print 语句,在某个时刻计数为 1。

基本上我想把计数的所有值加起来。

最佳答案

父进程做

{
close(pipes[1]);
read(pipes[0], &t, sizeof(t));
}

numForks 次。所以只有第一个 child 得到一个打开的写描述符pipes[1],每次都会覆盖t,只留下最后一个值。

关于c - 如何使用管道来保留子进程中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20293095/

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