I am writing a C program. I have defined a global variable whose value will be updated from the main function. But the problem is that it is not happening. Can you please tell me what am I doing wrong. Here is my code.
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<signal.h>
#include<sys/wait.h>
extern int DELAY=10;
int DATA1=0;
int DATA2=0;
int main(){
generateData(0);
return 0;
}
void generateData(int x){
int y=x;
int p1,p2;
p1=fork();
p2=fork();
if(p1==0 && p2>0){
for(int i=0;i<3;i++){
printf("p1:%d\n",i);
sleep(1);
if(x==0){
x=1;
DATA1=x;
}
else if(x==1){
x=0;
DATA1=x;
}
// printf("%d\n",DATA1);
// l=DATA1;
printf("DATA1:%d\n",DATA1);
}
}
else if(p2==0 && p1>0){
for(int i=0;i<3;i++){
printf("p2:%d\n",i);
sleep(10);
if(y==0){
y=1;
DATA2=y;
}
else if(y==1){
y=0;
DATA2=y;
}
// m=DATA2;
printf("DATA2:%d\n",DATA2);
}
}
else if(p1>0 && p2>0){
wait(0);
printf("DATA1=%d, DATA2=%d\n",DATA1,DATA2);
kill(p1,SIGKILL);
kill(p2,SIGKILL);
checkTruthTable(DATA1,DATA2);
}
}
int checkTruthTable(int x, int y){
return 0;
}
I want to update value of DATA1 and DATA2 from generateData function.When I am trying to print the data for the third else if loop it is showing me DATA1=0, DATA2=0
Result:
p2:0
p1:0
DATA1:1
p1:1
DATA1:0
p1:2
DATA1:1
DATA1=0, DATA2=0
generateData()but the parent executes last elseif() block and you are not updating any variables there. Even though the child updates it wont reflect in parents memory because child has seperate heap, stack, data-section.. etc.. Referfork()man page you will understand better.