How to get return value from child process to parent?

前端 未结 2 1970
走了就别回头了
走了就别回头了 2020-12-19 11:20

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.

2条回答
  •  遥遥无期
    2020-12-19 11:51

    If you can't use pipes, which would be the optimal solution here, you could save the result to a file that the parent would read from. Pass the name of the file to save the result to from parent to child. In your child process, you would do:

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

    Then in your parent process:

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

提交回复
热议问题