gpt4 book ai didi

c - 如何从子进程获取返回值给父进程?

转载 作者:太空狗 更新时间:2023-10-29 15:01:48 25 4
gpt4 key购买 nike

我应该将斐波那契数列前 12 项的总和从子进程返回到父进程,但父进程得到 377,父进程得到 30976

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
pid_t childpid;
int i, fib_sum=0, fib1=1, fib2=1, temp, status;

childpid=fork();

if(childpid!=0)
{
wait(&status);
fprintf(stderr, "%d\n", status);
}
else
{
for(i=1; i<=12; i++)
{
temp=fib1;
fib_sum=fib1+fib2;
fib1=fib_sum;
fib2=temp;
}
fprintf(stderr, "%d\n", fib_sum);
return fib_sum;
}
}

我做错了什么?

最佳答案

I'm supposed to return the sum of first 12 terms of Fibonacci series from child process to parent one but instead having 377, parent gets 30976.

进程退出状态的值有限,因此它不是在子进程和父进程之间传递值的最佳方式。

解决方案之一是使用管道传递计算值。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[])
{
pid_t childpid;
int i, fib_sum=0, fib1=1, fib2=1, temp, status;

int fd[2];
int val = 0;

// create pipe descriptors
pipe(fd);

childpid = fork();
if(childpid != 0) // parent
{
close(fd[1]);
// read the data (blocking operation)
read(fd[0], &val, sizeof(val));

printf("Parent received value: %d\n", val);
// close the read-descriptor
close(fd[0]);
}
else // child
{
// writing only, no need for read-descriptor:
close(fd[0]);

for(i=1; i<=12; i++)
{
temp = fib1;
fib_sum = fib1+fib2;
fib1 = fib_sum;
fib2 = temp;
}

// send the value on the write-descriptor:
write(fd[1], &fib_sum, sizeof(fib_sum));
printf("Child send value: %d\n", fib_sum);

// close the write descriptor:
close(fd[1]);

return fib_sum;
}
}

测试:

Child send value: 377                                                                                                                         
Parent received value: 377

关于c - 如何从子进程获取返回值给父进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581349/

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