Manny
Manny

Reputation: 679

using fork system call

This is the first time i am using fork, i want the parent process to calculate the sum, and the child to provide input to the sum in parent process or vice versa, but i am not able to do it, they work as two independent process!! how can i do this, when i give input as 1 and 2, parent must return sum as 3

int main()  {

    int num1 = 0, num2 = 0, sum = 0;
    pid_t pid;
    pid = fork();
    if(pid == -1)
        perror("fork");
    if(pid > 1)
    {
        wait(NULL);
        printf("sum:%d\n",sum = num1 + num2);
    }
    if(!pid)
    {
        printf("Enter two number\n");
        scanf("%d %d", &num1, &num2);
    }

}  

Upvotes: 1

Views: 1976

Answers (2)

Shashank
Shashank

Reputation: 34

once if you use fork system call in your program it creates another process you can't return from one process to another process ( child process to parent ) so if you want to communicate between two process using fork system call means use unnamed pipe (one method of inter process communication)

Upvotes: 0

xaxxon
xaxxon

Reputation: 19801

Once you fork, each process gets its own copy of the variables (at least from a logical perspective -- see copy-on-write for more data), so you can't change things after the fork and expect the other process to see those changes.

You'll need to use some sort of inter-process communication:

http://en.wikipedia.org/wiki/Inter-process_communication

You may want to look at this question for more details:

UNIX Pipes Between Child Processes

Upvotes: 2

Related Questions