Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c - How to get return value from child process to parent?

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
", status);
    }
    else
    {
        for(i=1; i<=12; i++)
        {
            temp=fib1;
            fib_sum=fib1+fib2;
            fib1=fib_sum;
            fib2=temp;
        }
        fprintf(stderr, "%d
", fib_sum);
        return fib_sum;
    }
}

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", 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
", fib_sum);

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

        return fib_sum;
    }
}

Test:

Child send value: 377                                                                                                                         
Parent received value: 377

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...