tags:

views:

121

answers:

3

Program calculates sum of numbers from 1 to N.. Child process calculates sum of EVEN numbers. Parent process calculates sum of odd numbers. I want to get the return value of child process in parent process. How do i do that

#include<stdio.h>
#include<errno.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>

int main()
{
    int N;
    int id;
    int fd_result;;

    printf("Enter N till which you want the sum: \n");
    scanf("%d",&N);
    if ((fd_result=creat("result", 600))== -1)
    {
        perror("Error creating file");
        exit(1);
    }
    if ((fd_result=open("result",O_TRUNC | O_RDWR)) == -1)
    {
        perror("Error Opening file");
        exit(1);
    }
    if ((id=fork())<0)
    {
        perror("Error occurred forking....!");
        exit(errno);
    }
    if (id == 0)
    {
        int i;
        int sum=0;
        for (i=0;i<=N;i=i+2)
            sum+=i;
        printf("Child sum: %d",sum);
        if (write(fd_result,&sum,sizeof(int))==-1) perror("Error writing to file");
        _exit(0);
    }


    if (id > 0)
    {
        int i;
        int sum=0;
        int sum_odd;
        for (i=1;i<=N;i=i+2)
            sum+=i;
        lseek(fd_result,0,SEEK_SET);
        read(fd_result,&sum_odd,sizeof(int));
        printf("\nThe sum is: %d",sum+(int)sum_odd);
    }

    close(fd_result);
    return 0;
}

Pls tell me how do I get the return value of child process?

+6  A: 

What you are looking for is wait() or waitpid().

dtmilano
How do i actually use it? I am not able to get it. Actually its the first time I have written a fork() program...pls help
shadyabhi
In the parent call waitpid(-1,
dtmilano
afterwards,printf("status returned: %d",WEXITSTATUS(status));...
shadyabhi
A: 

Like dtmilano said you should use wait or waitpid, depending or need.

But maybe you should split your program in two parts and execute the son with exec. When you make fork your child process receive pid equal 0 and I don't know if you try to wait signals of process with pid 0 will work fine.

Anyway you can pass, though it's not the best way, the value calculated by your child process through exit.

Rafael
A: 

If you want to preserve the return value for signaling a successful or failure exit status, you can call pipe(2) before forking to set up a separate channel between parent and child.

pra