use Fork on linux

Asked

Viewed 81 times

0

I started studying the function fork(2) recently and I tried to create a small program to calculate the sum of two numbers. The algorithm is made for the child process to receive two values while the parent process is responsible for the calculation.

The problem is that the value of the variables is not passing from one side to the other. The code is as follows::

#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include <malloc.h>
static int d,p;
double pi;

int main(void)
{
int *m = malloc(10);
*m=1;
pid_t pid;

pid = fork();

if(pid == 0){
    printf("espera por dados (child)\n");
    scanf("%d",&p);
    *m=p;
    scanf("%d",&d);
    *(m+1)=d;
    exit(0);
}
else{
    pid = wait(NULL);
    pi=(double)p/(double)d;
}
printf("O valor da soma é %d",pi);
}

Can someone explain to me what’s wrong with this code?

1 answer

0

After a fork() child and parent processes virtually no longer share the same memory area. To do this you must use some type of IPC communication. If all you want is to transfer two int son to father recommend use pipe() (look for "Fork pipe" on Google). If you need a more sophisticated data transfer recommend studying the IPC mechanisms available on the operating system you are using.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.