I recently learned about the functioning of fork() in c++. I came across 2 questions which i can't find any reasons about.
- Here although i am getting the same address of a in both child and parent but the values are different can you please explain reason for this behaviour.
- Is there any way such that making any change in parent gets reflected in child or vice versa without using files to communicate between the two
#include <bits/stdc++.h>
#include<unistd.h>
#include<stdlib.h>
using namespace std;
signed main() {
int *a=(int *)malloc(sizeof(int));
*a=5;
cout<<a<<endl;
int pid=fork();
if(pid!=0)
{
sleep(2);
*a+=2;
cout<<a<<" "<<*a<<" "<<"PARENT"<<endl;
}
else
{
*a+=1;
cout<<a<<" "<<*a<<" "<<"CHILD"<<endl;
}
}
This is the output of above code.
0x561d5c19beb0
0x561d5c19beb0 6 CHILD
0x561d5c19beb0 7 PARENT
I was expecting the answer to be
0x561d5c19beb0
0x561d5c19beb0 6 CHILD
0x561d5c19beb0 8 PARENT
OR
0x561d5c19beb0
<different_value> 6 CHILD
0x561d5c19beb0 7 PARENT
But the answer seems completely unintuitive and illogical.