如何从子进程获取返回值到父进程?

时间:2018-03-30 20:57:27

标签: c fork parent-child ipc child-process

我应该将斐波纳契系列的前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;
    }
}

我做错了什么?

2 个答案:

答案 0 :(得分:3)

  

我应该返回Fibonacci系列前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;

    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

答案 1 :(得分:2)

如果您不能use pipes,这将是最佳解决方案,您可以将结果保存到父级可以读取的文件中。传递文件名以将结果保存到父级到子级。在您的子进程中,您可以:

int main(int argc, char *argv[])
{
    int fib_sum=0;
    if (argc <= 1)
    {
        print_usage();
        return 1;
    }
    //... calculate fib_sum
    FILE *f = fopen(argv[1], "w");
    if (f == NULL)
    {
        printf("Error opening file!\n");
        return 1;
    }
    fprintf(f, "%d", fib_sum);
    return 0;
}

然后在您的父进程中:

int n = 0;
FILE* f;
//... spawn child and wait
FILE *f = fopen(file_name, "r");
fscanf(f, "%d", &n);
相关问题