如何获得子进程到父进程的返回值? [英] How to get return value from child process to parent?

查看:326
本文介绍了如何获得子进程到父进程的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该将斐波那契数列的前12个项的总和从子过程返回给父项,但取而代之的是377,父项得到30976.

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;

    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;
    }
}

我在做什么错了?

推荐答案

我应该返回斐波那契数列的前12个项的总和 从子进程到父进程,而父进程却只有377 30976.

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.

进程退出状态的值受到限制,因此,这不是在父子之间传递值的最佳方法.

Process exit status is limited in value, therefore it is not the best way to communicate a value between child and parent.

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

One of the solution is to pass the calculated value using pipes.

#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

这篇关于如何获得子进程到父进程的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆